-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathimage_registry.go
More file actions
364 lines (311 loc) · 10.8 KB
/
image_registry.go
File metadata and controls
364 lines (311 loc) · 10.8 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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package util //nolint:revive // util is an acceptable package name in this context
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"sort"
"strings"
ocpconfigv1 "github.com/openshift/api/config/v1"
ocpconfigv1alpha1 "github.com/openshift/api/config/v1alpha1"
mc "github.com/openshift/api/machineconfiguration/v1"
ocpicsp "github.com/openshift/api/operator/v1alpha1"
"github.com/openstack-k8s-operators/lib-common/modules/common/helper"
corev1 "k8s.io/api/core/v1"
k8s_errors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
// machineConfigIgnition - holds the relevant parts of the ignition file that we need to create
// the registries.conf on the dataplane nodes.
type machineConfigIgnition struct {
Ignition struct {
Version string `json:"version"`
} `json:"ignition"`
Storage struct {
Files []struct {
Contents struct {
Compression string `json:"compression,omitempty"`
Source string `json:"source"`
} `json:"contents"`
Mode int `json:"mode,omitempty"`
Overwrite bool `json:"overwrite,omitempty"`
Path string `json:"path"`
} `json:"files"`
} `json:"storage"`
}
// HasMirrorRegistries checks if OCP has IDMS/ICSP mirror registries configured.
// Note: The presence of IDMS/ICSP doesn't necessarily mean the cluster is disconnected.
// Mirror registries may be configured for other reasons (performance, policy, caching, etc.).
// Returns false without error if the CRDs don't exist (non-OpenShift cluster).
func HasMirrorRegistries(ctx context.Context, helper *helper.Helper) (bool, error) {
// Check IDMS first (current API), then fall back to ICSP (deprecated)
idmsList := &ocpconfigv1.ImageDigestMirrorSetList{}
if err := helper.GetClient().List(ctx, idmsList); err != nil {
if !IsNoMatchError(err) {
return false, err
}
// CRD doesn't exist, continue to check ICSP
} else if len(idmsList.Items) > 0 {
return true, nil
}
icspList := &ocpicsp.ImageContentSourcePolicyList{}
if err := helper.GetClient().List(ctx, icspList); err != nil {
if !IsNoMatchError(err) {
return false, err
}
// CRD doesn't exist, fall through to return false
} else if len(icspList.Items) > 0 {
return true, nil
}
return false, nil
}
func collectMirrorScopes(scopes map[string]struct{}, values []string) []string {
for _, value := range values {
scope := normalizeImageScope(value)
if scope != "" {
scopes[scope] = struct{}{}
}
}
if len(scopes) == 0 {
return nil
}
result := make([]string, 0, len(scopes))
for scope := range scopes {
result = append(result, scope)
}
sort.Strings(result)
return result
}
// GetMirrorRegistryScopes returns the configured mirror scopes, preferring IDMS
// and falling back to ICSP only when no IDMS mirror scopes are present.
// The returned values are normalized and de-duplicated for policy matching.
func GetMirrorRegistryScopes(ctx context.Context, helper *helper.Helper) ([]string, error) {
idmsList := &ocpconfigv1.ImageDigestMirrorSetList{}
if err := helper.GetClient().List(ctx, idmsList); err != nil {
if !IsNoMatchError(err) {
return nil, err
}
} else {
scopes := map[string]struct{}{}
for _, idms := range idmsList.Items {
for _, mirrorSet := range idms.Spec.ImageDigestMirrors {
mirrorValues := make([]string, 0, len(mirrorSet.Mirrors))
for _, mirror := range mirrorSet.Mirrors {
mirrorValues = append(mirrorValues, string(mirror))
}
result := collectMirrorScopes(scopes, mirrorValues)
if len(result) > 0 {
return result, nil
}
}
}
}
icspList := &ocpicsp.ImageContentSourcePolicyList{}
if err := helper.GetClient().List(ctx, icspList); err != nil {
if !IsNoMatchError(err) {
return nil, err
}
} else {
scopes := map[string]struct{}{}
for _, icsp := range icspList.Items {
for _, mirrorSet := range icsp.Spec.RepositoryDigestMirrors {
_ = collectMirrorScopes(scopes, mirrorSet.Mirrors)
}
}
return collectMirrorScopes(scopes, nil), nil
}
return nil, nil
}
// IsNoMatchError checks if the error indicates that a CRD/resource type doesn't exist
func IsNoMatchError(err error) bool {
errStr := err.Error()
// Check for "no matches for kind" type errors which indicate the CRD doesn't exist.
// Also check for "no kind is registered" which occurs when the type isn't in the scheme.
return strings.Contains(errStr, "no matches for kind") ||
strings.Contains(errStr, "no kind is registered")
}
// GetMCRegistryConf - will unmarshal the MachineConfig ignition file the machineConfigIgnition object.
// This is then parsed and the base64 decoded string is returned.
func GetMCRegistryConf(ctx context.Context, helper *helper.Helper) (string, error) {
var registriesConf string
masterMachineConfig, err := getMachineConfig(ctx, helper)
if err != nil {
return registriesConf, err
}
config := machineConfigIgnition{}
registriesConf, err = config.formatRegistriesConfString(&masterMachineConfig)
if err != nil {
return registriesConf, err
}
return registriesConf, nil
}
func (mci *machineConfigIgnition) removePrefixFromB64String() (string, error) {
const b64Prefix string = "data:text/plain;charset=utf-8;base64,"
if strings.HasPrefix(mci.Storage.Files[0].Contents.Source, b64Prefix) {
return mci.Storage.Files[0].Contents.Source[len(b64Prefix):], nil
}
return "", fmt.Errorf("no b64prefix found in MachineConfig")
}
func (mci *machineConfigIgnition) formatRegistriesConfString(machineConfig *mc.MachineConfig) (string, error) {
var (
err error
rawConfigString string
configString []byte
)
err = json.Unmarshal([]byte(machineConfig.Spec.Config.Raw), &mci)
if err != nil {
return "", err
}
rawConfigString, err = mci.removePrefixFromB64String()
if err != nil {
return "", err
}
configString, err = base64.StdEncoding.DecodeString(rawConfigString)
if err != nil {
return "", err
}
return string(configString), nil
}
func masterMachineConfigBuilder(machineConfigRegistries string) mc.MachineConfig {
return mc.MachineConfig{
ObjectMeta: metav1.ObjectMeta{
Name: machineConfigRegistries,
Namespace: "",
},
}
}
func getMachineConfig(ctx context.Context, helper *helper.Helper) (mc.MachineConfig, error) {
const machineConfigRegistries string = "99-master-generated-registries"
masterMachineConfig := masterMachineConfigBuilder(machineConfigRegistries)
err := helper.GetClient().Get(ctx,
types.NamespacedName{
Name: masterMachineConfig.Name, Namespace: masterMachineConfig.Namespace,
}, &masterMachineConfig)
if err != nil {
return masterMachineConfig, err
}
return masterMachineConfig, nil
}
// SigstorePolicyInfo contains the EDPM-relevant parts of a ClusterImagePolicy.
type SigstorePolicyInfo struct {
MirrorRegistry string
CosignKeyData string
SignedPrefix string
}
func normalizeImageScope(scope string) string {
return strings.TrimSuffix(strings.TrimSpace(scope), "/")
}
func clusterImagePolicyScopeMatchesMirror(policyScope string, mirrorScope string) bool {
policyScope = normalizeImageScope(policyScope)
mirrorScope = normalizeImageScope(mirrorScope)
if policyScope == "" || mirrorScope == "" {
return false
}
if strings.HasPrefix(policyScope, "*.") {
mirrorHost := strings.SplitN(mirrorScope, "/", 2)[0]
suffix := strings.TrimPrefix(policyScope, "*")
return strings.HasSuffix(mirrorHost, suffix)
}
return mirrorScope == policyScope || strings.HasPrefix(mirrorScope, policyScope+"/")
}
// GetSigstoreImagePolicy checks if OCP has a ClusterImagePolicy configured
// with sigstore signature verification for one of the mirror registries in use.
// Returns policy info if a relevant policy is found, nil if no policy exists.
// Returns nil without error if the ClusterImagePolicy CRD is not installed.
func GetSigstoreImagePolicy(ctx context.Context, helper *helper.Helper, mirrorScopes []string) (*SigstorePolicyInfo, error) {
if len(mirrorScopes) == 0 {
return nil, nil
}
policyList := &ocpconfigv1alpha1.ClusterImagePolicyList{}
if err := helper.GetClient().List(ctx, policyList); err != nil {
if IsNoMatchError(err) {
return nil, nil
}
return nil, err
}
var matches []string
var match *SigstorePolicyInfo
for _, policy := range policyList.Items {
if policy.Name == "openshift" {
continue
}
if policy.Spec.Policy.RootOfTrust.PolicyType != ocpconfigv1alpha1.PublicKeyRootOfTrust {
continue
}
if policy.Spec.Policy.RootOfTrust.PublicKey == nil {
continue
}
keyData := policy.Spec.Policy.RootOfTrust.PublicKey.KeyData
if len(keyData) == 0 {
continue
}
if len(policy.Spec.Scopes) == 0 {
continue
}
signedPrefix := ""
if policy.Spec.Policy.SignedIdentity.MatchPolicy == ocpconfigv1alpha1.IdentityMatchPolicyRemapIdentity &&
policy.Spec.Policy.SignedIdentity.PolicyMatchRemapIdentity != nil {
signedPrefix = string(policy.Spec.Policy.SignedIdentity.PolicyMatchRemapIdentity.SignedPrefix)
}
for _, scope := range policy.Spec.Scopes {
policyScope := normalizeImageScope(string(scope))
if policyScope == "" {
continue
}
matchesMirror := false
for _, mirrorScope := range mirrorScopes {
if clusterImagePolicyScopeMatchesMirror(policyScope, mirrorScope) {
matchesMirror = true
break
}
}
if !matchesMirror {
continue
}
matches = append(matches, fmt.Sprintf("%s (%s)", policy.Name, policyScope))
match = &SigstorePolicyInfo{
MirrorRegistry: policyScope,
CosignKeyData: base64.StdEncoding.EncodeToString(keyData),
SignedPrefix: signedPrefix,
}
}
}
if len(matches) > 1 {
sort.Strings(matches)
return nil, fmt.Errorf(
"expected exactly one ClusterImagePolicy matching mirror registries, found %d: %s",
len(matches), strings.Join(matches, ", "),
)
}
return match, nil
}
// GetMirrorRegistryCACerts retrieves CA certificates from image.config.openshift.io/cluster.
// Returns nil without error if:
// - not on OpenShift (Image CRD doesn't exist)
// - no additional CA is configured
// - the referenced ConfigMap doesn't exist
func GetMirrorRegistryCACerts(ctx context.Context, helper *helper.Helper) (map[string]string, error) {
imageConfig := &ocpconfigv1.Image{}
if err := helper.GetClient().Get(ctx, types.NamespacedName{Name: "cluster"}, imageConfig); err != nil {
if IsNoMatchError(err) {
return nil, nil
}
return nil, fmt.Errorf("failed to get image.config.openshift.io/cluster: %w", err)
}
if imageConfig.Spec.AdditionalTrustedCA.Name == "" {
return nil, nil
}
caConfigMap := &corev1.ConfigMap{}
if err := helper.GetClient().Get(ctx, types.NamespacedName{
Name: imageConfig.Spec.AdditionalTrustedCA.Name,
Namespace: "openshift-config",
}, caConfigMap); err != nil {
if k8s_errors.IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("failed to get ConfigMap %s in openshift-config: %w",
imageConfig.Spec.AdditionalTrustedCA.Name, err)
}
return caConfigMap.Data, nil
}