-
Notifications
You must be signed in to change notification settings - Fork 500
/
clusterimagepolicy_types.go
296 lines (257 loc) · 8.46 KB
/
clusterimagepolicy_types.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// 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 clusterimagepolicy
import (
"context"
"crypto"
"crypto/x509"
"encoding/json"
"encoding/pem"
"github.com/google/go-containerregistry/pkg/authn/k8schain"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/pkg/errors"
"github.com/sigstore/cosign/pkg/apis/cosigned/v1alpha1"
ociremote "github.com/sigstore/cosign/pkg/oci/remote"
"knative.dev/pkg/apis"
kubeclient "knative.dev/pkg/client/injection/kube/client"
"knative.dev/pkg/logging"
)
// ClusterImagePolicy defines the images that go through verification
// and the authorities used for verification.
// This is the internal representation of the external v1alpha1.ClusterImagePolicy.
// KeyRef does not store secretRefs in internal representation.
// KeyRef does store parsed publicKeys from Data in internal representation.
type ClusterImagePolicy struct {
Images []v1alpha1.ImagePattern `json:"images"`
Authorities []Authority `json:"authorities"`
// Policy is an optional policy used to evaluate the results of valid
// Authorities. Will not get evaluated unless at least one Authority
// succeeds.
Policy *AttestationPolicy `json:"policy,omitempty"`
}
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.
Name string `json:"name"`
// +optional
Key *KeyRef `json:"key,omitempty"`
// +optional
Keyless *KeylessRef `json:"keyless,omitempty"`
// +optional
Sources []v1alpha1.Source `json:"source,omitempty"`
// +optional
CTLog *v1alpha1.TLog `json:"ctlog,omitempty"`
// RemoteOpts are not marshalled because they are an unsupported type
// RemoteOpts will be populated by the Authority UnmarshalJSON override
// +optional
RemoteOpts []ociremote.Option `json:"-"`
// +optional
Attestations []AttestationPolicy `json:"attestations,omitempty"`
}
// This references a public verification key stored in
// a secret in the cosign-system namespace.
type KeyRef struct {
// Data contains the inline public key
// +optional
Data string `json:"data,omitempty"`
// PublicKeys are not marshalled because JSON unmarshalling
// errors for *big.Int
// +optional
PublicKeys []crypto.PublicKey `json:"-"`
}
type KeylessRef struct {
// +optional
URL *apis.URL `json:"url,omitempty"`
// +optional
Identities []v1alpha1.Identity `json:"identities,omitempty"`
// +optional
CACert *KeyRef `json:"ca-cert,omitempty"`
}
type AttestationPolicy struct {
// Name of the Attestation
Name string `json:"name"`
// PredicateType to attest, one of the accepted in verify-attestation
PredicateType string `json:"predicateType"`
// Type specifies how to evaluate policy, only rego/cue are understood.
Type string `json:"type,omitempty"`
// Data is the inlined version of the Policy used to evaluate the
// Attestation.
Data string `json:"data,omitempty"`
}
// UnmarshalJSON populates the PublicKeys using Data because
// JSON unmashalling errors for *big.Int
func (k *KeyRef) UnmarshalJSON(data []byte) error {
var publicKeys []crypto.PublicKey
var err error
ret := make(map[string]string)
if err = json.Unmarshal(data, &ret); err != nil {
return err
}
k.Data = ret["data"]
if ret["data"] != "" {
publicKeys, err = ConvertKeyDataToPublicKeys(ret["data"])
if err != nil {
return err
}
}
k.PublicKeys = publicKeys
return nil
}
// UnmarshalJSON populates the authority with the remoteOpts
// from authority sources
func (a *Authority) UnmarshalJSON(data []byte) error {
// Create a new type to avoid recursion
type RawAuthority Authority
var rawAuthority RawAuthority
err := json.Unmarshal(data, &rawAuthority)
if err != nil {
return err
}
// Determine additional RemoteOpts
if len(rawAuthority.Sources) > 0 {
for _, source := range rawAuthority.Sources {
if targetRepoOverride, err := name.NewRepository(source.OCI); err != nil {
return errors.Wrap(err, "failed to determine source")
} else if (targetRepoOverride != name.Repository{}) {
rawAuthority.RemoteOpts = append(rawAuthority.RemoteOpts, ociremote.WithTargetRepository(targetRepoOverride))
}
}
}
// Set the new type instance to casted original
*a = Authority(rawAuthority)
return nil
}
// SourceSignaturePullSecretsOpts creates the signaturePullSecrets remoteOpts
// This is not stored in the Authority under RemoteOpts as the namespace can be different
func (a *Authority) SourceSignaturePullSecretsOpts(ctx context.Context, namespace string) ([]ociremote.Option, error) {
var ret []ociremote.Option
for _, source := range a.Sources {
if len(source.SignaturePullSecrets) > 0 {
signaturePullSecrets := make([]string, 0, len(source.SignaturePullSecrets))
for _, s := range source.SignaturePullSecrets {
signaturePullSecrets = append(signaturePullSecrets, s.Name)
}
opt := k8schain.Options{
Namespace: namespace,
ImagePullSecrets: signaturePullSecrets,
}
kc, err := k8schain.New(ctx, kubeclient.Get(ctx), opt)
if err != nil {
logging.FromContext(ctx).Errorf("failed creating keychain: %+v", err)
return nil, err
}
ret = append(ret, ociremote.WithRemoteOptions(remote.WithAuthFromKeychain(kc)))
}
}
return ret, nil
}
func ConvertClusterImagePolicyV1alpha1ToWebhook(in *v1alpha1.ClusterImagePolicy) *ClusterImagePolicy {
copyIn := in.DeepCopy()
outAuthorities := make([]Authority, 0)
for _, authority := range copyIn.Spec.Authorities {
outAuthority := convertAuthorityV1Alpha1ToWebhook(authority)
outAuthorities = append(outAuthorities, *outAuthority)
}
// If there's a ClusterImagePolicy level AttestationPolicy, convert it here.
var cipAttestationPolicy *AttestationPolicy
if in.Spec.Policy != nil {
cipAttestationPolicy = &AttestationPolicy{
Type: in.Spec.Policy.Type,
Data: in.Spec.Policy.Data,
}
}
return &ClusterImagePolicy{
Images: copyIn.Spec.Images,
Authorities: outAuthorities,
Policy: cipAttestationPolicy,
}
}
func convertAuthorityV1Alpha1ToWebhook(in v1alpha1.Authority) *Authority {
keyRef := convertKeyRefV1Alpha1ToWebhook(in.Key)
keylessRef := convertKeylessRefV1Alpha1ToWebhook(in.Keyless)
attestations := convertAttestationsV1Alpha1ToWebhook(in.Attestations)
return &Authority{
Name: in.Name,
Key: keyRef,
Keyless: keylessRef,
Sources: in.Sources,
CTLog: in.CTLog,
Attestations: attestations,
}
}
func convertAttestationsV1Alpha1ToWebhook(in []v1alpha1.Attestation) []AttestationPolicy {
ret := []AttestationPolicy{}
for _, inAtt := range in {
outAtt := AttestationPolicy{
Name: inAtt.Name,
PredicateType: inAtt.PredicateType,
}
if inAtt.Policy != nil {
outAtt.Type = inAtt.Policy.Type
outAtt.Data = inAtt.Policy.Data
}
ret = append(ret, outAtt)
}
return ret
}
func convertKeyRefV1Alpha1ToWebhook(in *v1alpha1.KeyRef) *KeyRef {
if in == nil {
return nil
}
return &KeyRef{
Data: in.Data,
}
}
func convertKeylessRefV1Alpha1ToWebhook(in *v1alpha1.KeylessRef) *KeylessRef {
if in == nil {
return nil
}
CACertRef := convertKeyRefV1Alpha1ToWebhook(in.CACert)
return &KeylessRef{
URL: in.URL,
Identities: in.Identities,
CACert: CACertRef,
}
}
func parsePEMKey(b []byte) ([]*pem.Block, bool) {
pemKey, rest := pem.Decode(b)
valid := true
if pemKey == nil {
return nil, false
}
pemBlocks := []*pem.Block{pemKey}
if len(rest) > 0 {
list, check := parsePEMKey(rest)
return append(pemBlocks, list...), check
}
return pemBlocks, valid
}
func ConvertKeyDataToPublicKeys(pubKey string) ([]crypto.PublicKey, error) {
keys := []crypto.PublicKey{}
pems, validPEM := parsePEMKey([]byte(pubKey))
if !validPEM {
// TODO: If it is not valid report the error instead of ignore the key
return keys, nil
}
for _, p := range pems {
key, err := x509.ParsePKIXPublicKey(p.Bytes)
if err != nil {
return nil, err
}
keys = append(keys, key.(crypto.PublicKey))
}
return keys, nil
}