This repository was archived by the owner on Sep 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathverifier.go
More file actions
200 lines (176 loc) · 5.94 KB
/
Copy pathverifier.go
File metadata and controls
200 lines (176 loc) · 5.94 KB
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
// Copyright 2023 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 policy
import (
"context"
"errors"
"fmt"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/remote"
ociremote "github.com/sigstore/cosign/v2/pkg/oci/remote"
"github.com/sigstore/policy-controller/pkg/apis/config"
"github.com/sigstore/policy-controller/pkg/webhook"
webhookcip "github.com/sigstore/policy-controller/pkg/webhook/clusterimagepolicy"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/apis"
)
// Verifier is the interface for checking that a given image digest satisfies
// the policies backing this interface.
type Verifier interface {
// Verify checks that the provided reference satisfies the backing policies.
//
// For policies specifying `match:` criteria with apiVersion/kind, the
// TypeMeta should be associated with `ctx` here using:
// webhook.GetIncludeTypeMeta(ctx)
//
// For policies specifying `match:` criteria with label selectors, the
// ObjectMeta should be associated with `ctx` here using:
// webhook.GetIncludeObjectMeta(ctx)
Verify(context.Context, name.Reference, authn.Keychain, ...ociremote.Option) error
}
// WarningWriter is used to surface warning messages in a manner that
// is customizable by callers that's suitable for their execution
// environment. The signature is intended to match the standard format string
// signature (e.g. Printf, Infof, Logf, Errorf, Fatalf, ...), so functions like
// log.Printf or t.Errorf can be passed here directly.
type WarningWriter func(string, ...interface{})
// Compile turns a Verification into an executable Verifier.
// Any compilation errors are returned here.
func Compile(ctx context.Context, v Verification, ww WarningWriter) (Verifier, error) {
if err := v.Validate(ctx); err != nil {
return nil, err
}
ipc, err := gather(ctx, v, ww)
if err != nil {
// This should never hit for validated policies.
return nil, err
}
return &impl{
verification: v,
ipc: ipc,
ww: ww,
}, nil
}
func gather(ctx context.Context, v Verification, ww WarningWriter) (*config.ImagePolicyConfig, error) {
pol := *v.Policies
ipc := &config.ImagePolicyConfig{
Policies: make(map[string]webhookcip.ClusterImagePolicy, len(pol)),
}
for i, p := range pol {
content, err := p.fetch(ctx)
if err != nil {
return nil, err
}
l, warns, err := ParseClusterImagePolicies(ctx, content)
if err != nil {
// This path should be unreachable, since we already parse
// things during compilation.
return nil, fmt.Errorf("parsing policies: %w", err)
}
if warns != nil {
ww("policy %d: %v", i, warns)
}
// TODO(mattmoor): Add additional checks for unsupported things,
// like Match, IncludeSpec, etc.
for _, cip := range l {
cip.SetDefaults(ctx)
if _, ok := ipc.Policies[cip.Name]; ok {
ww("duplicate policy named %q, skipping", cip.Name)
continue
}
// We need to roundtrip the policy through JSON here because
// the compiled policy expects to be decoded from JSON and only
// sets up certain fields when being unmarshalled from JSON, so
// things like keyful verification only work when we roundtrip
// through JSON.
var compiled webhookcip.ClusterImagePolicy
if err := convert(webhookcip.ConvertClusterImagePolicyV1alpha1ToWebhook(cip), &compiled); err != nil {
ww("roundtripping policy %v", err)
continue
}
ipc.Policies[cip.Name] = compiled
}
}
return ipc, nil
}
type impl struct {
verification Verification
ipc *config.ImagePolicyConfig
ww WarningWriter
}
// Check that impl implements Verifier
var _ Verifier = (*impl)(nil)
// Verify implements Verifier
func (i *impl) Verify(ctx context.Context, ref name.Reference, kc authn.Keychain, opts ...ociremote.Option) error {
tm := getTypeMeta(ctx)
om := getObjectMeta(ctx)
matches, err := i.ipc.GetMatchingPolicies(ref.Name(), tm.Kind, tm.APIVersion, om.Labels)
if err != nil {
return err
}
if len(matches) == 0 {
switch i.verification.NoMatchPolicy {
case "allow":
return nil
case "warn":
i.ww("%s is uncovered by policy", ref)
case "deny":
return fmt.Errorf("%s is uncovered by policy", ref)
default:
// This is unreachable for a validated Verification.
return fmt.Errorf("unsupported noMatchPolicy: %q", i.verification.NoMatchPolicy)
}
}
// Add the keychain to our (optional) list of options.
opts = append(opts, ociremote.WithRemoteOptions(remote.WithAuthFromKeychain(kc)))
for _, p := range matches {
res, errs := webhook.ValidatePolicy(ctx, "" /* namespace */, ref, p, kc, opts...)
if res != nil { //nolint: revive
// Ignore the errors for other authorities if we got a policy result.
} else {
// If we didn't get a policy result, then surface any errors.
for _, err := range errs {
var fe *apis.FieldError
if errors.As(err, &fe) {
if warnFE := fe.Filter(apis.WarningLevel); warnFE != nil {
i.ww("%v", warnFE)
}
if errorFE := fe.Filter(apis.ErrorLevel); errorFE != nil {
return errorFE
}
} else {
return err
}
}
}
}
return nil
}
func getTypeMeta(ctx context.Context) (tm metav1.TypeMeta) {
raw := webhook.GetIncludeTypeMeta(ctx)
if raw == nil {
return
}
_ = convert(raw, &tm)
return
}
func getObjectMeta(ctx context.Context) (om metav1.ObjectMeta) {
raw := webhook.GetIncludeObjectMeta(ctx)
if raw == nil {
return
}
_ = convert(raw, &om)
return
}