Skip to content

Commit c801724

Browse files
committed
Accept a slice of remote.Option for cosign verification
If implemented this enable passing a keychain, an authenticator and a custom transport as remote.Option to the verifier. It enables contextual login, self-signed certificates and insecure registries. Signed-off-by: Soule BA <soule@weave.works>
1 parent 8bc36bc commit c801724

File tree

3 files changed

+143
-19
lines changed

3 files changed

+143
-19
lines changed

controllers/ocirepository_controller.go

+29-12
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ func (r *OCIRepositoryReconciler) reconcile(ctx context.Context, obj *sourcev1.O
297297
// reconcileSource fetches the upstream OCI artifact metadata and content.
298298
// If this fails, it records v1beta2.FetchFailedCondition=True on the object and returns early.
299299
func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sourcev1.OCIRepository, metadata *sourcev1.Artifact, dir string) (sreconcile.Result, error) {
300+
var verifyOpts []remote.Option
300301
ctxTimeout, cancel := context.WithTimeout(ctx, obj.Spec.Timeout.Duration)
301302
defer cancel()
302303

@@ -308,7 +309,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
308309
conditions.Delete(obj, sourcev1.SourceVerifiedCondition)
309310
}
310311

311-
options := r.craneOptions(ctxTimeout, obj.Spec.Insecure)
312+
craneOpts := r.craneOptions(ctxTimeout, obj.Spec.Insecure)
312313

313314
// Generate the registry credential keychain either from static credentials or using cloud OIDC
314315
keychain, err := r.keychain(ctx, obj)
@@ -320,7 +321,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
320321
conditions.MarkTrue(obj, sourcev1.FetchFailedCondition, e.Reason, e.Err.Error())
321322
return sreconcile.ResultEmpty, e
322323
}
323-
options = append(options, crane.WithAuthFromKeychain(keychain))
324+
craneOpts = append(craneOpts, crane.WithAuthFromKeychain(keychain))
324325

325326
if _, ok := keychain.(soci.Anonymous); obj.Spec.Provider != sourcev1.GenericOCIProvider && ok {
326327
auth, authErr := oidcAuth(ctxTimeout, obj.Spec.URL, obj.Spec.Provider)
@@ -333,8 +334,15 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
333334
return sreconcile.ResultEmpty, e
334335
}
335336
if auth != nil {
336-
options = append(options, crane.WithAuth(auth))
337+
craneOpts = append(craneOpts, crane.WithAuth(auth))
338+
verifyOpts = append(verifyOpts, remote.WithAuth(auth))
339+
} else {
340+
// If no auth is configured at all, use anonymous access
341+
verifyOpts = append(verifyOpts, remote.WithAuthFromKeychain(keychain))
337342
}
343+
} else {
344+
// we need to make sure not to pass a keychain and an auth option at the same time
345+
verifyOpts = append(verifyOpts, remote.WithAuthFromKeychain(keychain))
338346
}
339347

340348
// Generate the transport for remote operations
@@ -348,11 +356,12 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
348356
return sreconcile.ResultEmpty, e
349357
}
350358
if transport != nil {
351-
options = append(options, crane.WithTransport(transport))
359+
craneOpts = append(craneOpts, crane.WithTransport(transport))
360+
verifyOpts = append(verifyOpts, remote.WithTransport(transport))
352361
}
353362

354363
// Determine which artifact revision to pull
355-
url, err := r.getArtifactURL(obj, options)
364+
url, err := r.getArtifactURL(obj, craneOpts)
356365
if err != nil {
357366
if _, ok := err.(invalidOCIURLError); ok {
358367
e := serror.NewStalling(
@@ -370,7 +379,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
370379
}
371380

372381
// Get the upstream revision from the artifact digest
373-
revision, err := r.getRevision(url, options)
382+
revision, err := r.getRevision(url, craneOpts)
374383
if err != nil {
375384
e := serror.NewGeneric(
376385
fmt.Errorf("failed to determine artifact digest: %w", err),
@@ -401,7 +410,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
401410
} else if !obj.GetArtifact().HasRevision(revision) ||
402411
conditions.GetObservedGeneration(obj, sourcev1.SourceVerifiedCondition) != obj.Generation ||
403412
conditions.IsFalse(obj, sourcev1.SourceVerifiedCondition) {
404-
err := r.verifySignature(ctx, obj, url, keychain)
413+
err := r.verifySignature(ctx, obj, url, verifyOpts...)
405414
if err != nil {
406415
provider := obj.Spec.Verify.Provider
407416
if obj.Spec.Verify.SecretRef == nil {
@@ -425,7 +434,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
425434
}
426435

427436
// Pull artifact from the remote container registry
428-
img, err := crane.Pull(url, options...)
437+
img, err := crane.Pull(url, craneOpts...)
429438
if err != nil {
430439
e := serror.NewGeneric(
431440
fmt.Errorf("failed to pull artifact from '%s': %w", obj.Spec.URL, err),
@@ -585,15 +594,15 @@ func (r *OCIRepositoryReconciler) digestFromRevision(revision string) string {
585594

586595
// verifySignature verifies the authenticity of the given image reference url. First, it tries using a key
587596
// if a secret with a valid public key is provided. If not, it falls back to a keyless approach for verification.
588-
func (r *OCIRepositoryReconciler) verifySignature(ctx context.Context, obj *sourcev1.OCIRepository, url string, keychain authn.Keychain) error {
597+
func (r *OCIRepositoryReconciler) verifySignature(ctx context.Context, obj *sourcev1.OCIRepository, url string, opt ...remote.Option) error {
589598
ctxTimeout, cancel := context.WithTimeout(ctx, obj.Spec.Timeout.Duration)
590599
defer cancel()
591600

592601
provider := obj.Spec.Verify.Provider
593602
switch provider {
594603
case "cosign":
595604
defaultCosignOciOpts := []soci.Options{
596-
soci.WithAuthnKeychain(keychain),
605+
soci.WithRemoteOptions(opt...),
597606
}
598607

599608
ref, err := name.ParseReference(url)
@@ -807,8 +816,10 @@ func (r *OCIRepositoryReconciler) transport(ctx context.Context, obj *sourcev1.O
807816

808817
transport := remote.DefaultTransport.Clone()
809818
tlsConfig := transport.TLSClientConfig
819+
clientCert, withClientCert := certSecret.Data[oci.ClientCert]
820+
caCert, withCACert := certSecret.Data[oci.CACert]
810821

811-
if clientCert, ok := certSecret.Data[oci.ClientCert]; ok {
822+
if withClientCert {
812823
// parse and set client cert and secret
813824
if clientKey, ok := certSecret.Data[oci.ClientKey]; ok {
814825
cert, err := tls.X509KeyPair(clientCert, clientKey)
@@ -821,14 +832,20 @@ func (r *OCIRepositoryReconciler) transport(ctx context.Context, obj *sourcev1.O
821832
}
822833
}
823834

824-
if caCert, ok := certSecret.Data[oci.CACert]; ok {
835+
if withCACert {
825836
syscerts, err := x509.SystemCertPool()
826837
if err != nil {
827838
return nil, err
828839
}
829840
syscerts.AppendCertsFromPEM(caCert)
830841
tlsConfig.RootCAs = syscerts
831842
}
843+
844+
// If no cert is provided, verify that Insecure is set to true.
845+
if obj.Spec.Insecure && !withCACert && !withClientCert {
846+
tlsConfig.InsecureSkipVerify = true
847+
}
848+
832849
return transport, nil
833850
}
834851

internal/oci/verifier.go

+9-7
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import (
2020
"context"
2121
"crypto"
2222
"fmt"
23-
"github.com/google/go-containerregistry/pkg/authn"
23+
2424
"github.com/google/go-containerregistry/pkg/v1/remote"
2525
"github.com/sigstore/cosign/cmd/cosign/cli/fulcio"
2626
"github.com/sigstore/cosign/cmd/cosign/cli/rekor"
@@ -37,7 +37,7 @@ import (
3737
// options is a struct that holds options for verifier.
3838
type options struct {
3939
PublicKey []byte
40-
Keychain authn.Keychain
40+
ROpt []remote.Option
4141
}
4242

4343
// Options is a function that configures the options applied to a Verifier.
@@ -50,9 +50,11 @@ func WithPublicKey(publicKey []byte) Options {
5050
}
5151
}
5252

53-
func WithAuthnKeychain(keychain authn.Keychain) Options {
54-
return func(opts *options) {
55-
opts.Keychain = keychain
53+
// WithRemoteOptions is a functional option for overriding the default
54+
// remote options used by the verifier.
55+
func WithRemoteOptions(opts ...remote.Option) Options {
56+
return func(o *options) {
57+
o.ROpt = opts
5658
}
5759
}
5860

@@ -76,8 +78,8 @@ func NewVerifier(ctx context.Context, opts ...Options) (*Verifier, error) {
7678
return nil, err
7779
}
7880

79-
if o.Keychain != nil {
80-
co = append(co, ociremote.WithRemoteOptions(remote.WithAuthFromKeychain(o.Keychain)))
81+
if o.ROpt != nil {
82+
co = append(co, ociremote.WithRemoteOptions(o.ROpt...))
8183
}
8284

8385
checkOpts.RegistryClientOpts = co

internal/oci/verifier_test.go

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
Copyright 2022 The Flux authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package oci
18+
19+
import (
20+
"net/http"
21+
"reflect"
22+
"testing"
23+
24+
"github.com/google/go-containerregistry/pkg/authn"
25+
"github.com/google/go-containerregistry/pkg/v1/remote"
26+
)
27+
28+
func TestOptions(t *testing.T) {
29+
tests := []struct {
30+
name string
31+
opts []Options
32+
want *options
33+
}{{
34+
name: "no options",
35+
want: &options{},
36+
}, {
37+
name: "signature option",
38+
opts: []Options{WithPublicKey([]byte("foo"))},
39+
want: &options{
40+
PublicKey: []byte("foo"),
41+
ROpt: nil,
42+
},
43+
}, {
44+
name: "keychain option",
45+
opts: []Options{WithRemoteOptions(remote.WithAuthFromKeychain(authn.DefaultKeychain))},
46+
want: &options{
47+
PublicKey: nil,
48+
ROpt: []remote.Option{remote.WithAuthFromKeychain(authn.DefaultKeychain)},
49+
},
50+
}, {
51+
name: "keychain and authenticator option",
52+
opts: []Options{WithRemoteOptions(
53+
remote.WithAuth(&authn.Basic{Username: "foo", Password: "bar"}),
54+
remote.WithAuthFromKeychain(authn.DefaultKeychain),
55+
)},
56+
want: &options{
57+
PublicKey: nil,
58+
ROpt: []remote.Option{
59+
remote.WithAuth(&authn.Basic{Username: "foo", Password: "bar"}),
60+
remote.WithAuthFromKeychain(authn.DefaultKeychain),
61+
},
62+
},
63+
}, {
64+
name: "keychain, authenticator and transport option",
65+
opts: []Options{WithRemoteOptions(
66+
remote.WithAuth(&authn.Basic{Username: "foo", Password: "bar"}),
67+
remote.WithAuthFromKeychain(authn.DefaultKeychain),
68+
remote.WithTransport(http.DefaultTransport),
69+
)},
70+
want: &options{
71+
PublicKey: nil,
72+
ROpt: []remote.Option{
73+
remote.WithAuth(&authn.Basic{Username: "foo", Password: "bar"}),
74+
remote.WithAuthFromKeychain(authn.DefaultKeychain),
75+
remote.WithTransport(http.DefaultTransport),
76+
},
77+
},
78+
},
79+
}
80+
81+
for _, test := range tests {
82+
t.Run(test.name, func(t *testing.T) {
83+
o := options{}
84+
for _, opt := range test.opts {
85+
opt(&o)
86+
}
87+
if !reflect.DeepEqual(o.PublicKey, test.want.PublicKey) {
88+
t.Errorf("got %#v, want %#v", &o.PublicKey, test.want.PublicKey)
89+
}
90+
91+
if test.want.ROpt != nil {
92+
if len(o.ROpt) != len(test.want.ROpt) {
93+
t.Errorf("got %d remote options, want %d", len(o.ROpt), len(test.want.ROpt))
94+
}
95+
return
96+
}
97+
98+
if test.want.ROpt == nil {
99+
if len(o.ROpt) != 0 {
100+
t.Errorf("got %d remote options, want %d", len(o.ROpt), 0)
101+
}
102+
}
103+
})
104+
}
105+
}

0 commit comments

Comments
 (0)