Skip to content

Commit e2f4e5e

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 <[email protected]> refactor makeOptions Reduce complexity by replacing the functional options with a flat out conditional logic in makeOptions. Signed-off-by: Soule BA <[email protected]>
1 parent 95cbf40 commit e2f4e5e

File tree

4 files changed

+179
-41
lines changed

4 files changed

+179
-41
lines changed

controllers/ocirepository_controller.go

Lines changed: 62 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,8 @@ func (r *OCIRepositoryReconciler) reconcile(ctx context.Context, obj *sourcev1.O
299299
// reconcileSource fetches the upstream OCI artifact metadata and content.
300300
// If this fails, it records v1beta2.FetchFailedCondition=True on the object and returns early.
301301
func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sourcev1.OCIRepository, metadata *sourcev1.Artifact, dir string) (sreconcile.Result, error) {
302+
var auth authn.Authenticator
303+
302304
ctxTimeout, cancel := context.WithTimeout(ctx, obj.Spec.Timeout.Duration)
303305
defer cancel()
304306

@@ -310,8 +312,6 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
310312
conditions.Delete(obj, sourcev1.SourceVerifiedCondition)
311313
}
312314

313-
options := r.craneOptions(ctxTimeout, obj.Spec.Insecure)
314-
315315
// Generate the registry credential keychain either from static credentials or using cloud OIDC
316316
keychain, err := r.keychain(ctx, obj)
317317
if err != nil {
@@ -322,10 +322,10 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
322322
conditions.MarkTrue(obj, sourcev1.FetchFailedCondition, e.Reason, e.Err.Error())
323323
return sreconcile.ResultEmpty, e
324324
}
325-
options = append(options, crane.WithAuthFromKeychain(keychain))
326325

327326
if _, ok := keychain.(soci.Anonymous); obj.Spec.Provider != sourcev1.GenericOCIProvider && ok {
328-
auth, authErr := oidcAuth(ctxTimeout, obj.Spec.URL, obj.Spec.Provider)
327+
var authErr error
328+
auth, authErr = oidcAuth(ctxTimeout, obj.Spec.URL, obj.Spec.Provider)
329329
if authErr != nil && !errors.Is(authErr, oci.ErrUnconfiguredProvider) {
330330
e := serror.NewGeneric(
331331
fmt.Errorf("failed to get credential from %s: %w", obj.Spec.Provider, authErr),
@@ -334,9 +334,6 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
334334
conditions.MarkTrue(obj, sourcev1.FetchFailedCondition, e.Reason, e.Err.Error())
335335
return sreconcile.ResultEmpty, e
336336
}
337-
if auth != nil {
338-
options = append(options, crane.WithAuth(auth))
339-
}
340337
}
341338

342339
// Generate the transport for remote operations
@@ -349,12 +346,11 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
349346
conditions.MarkTrue(obj, sourcev1.FetchFailedCondition, e.Reason, e.Err.Error())
350347
return sreconcile.ResultEmpty, e
351348
}
352-
if transport != nil {
353-
options = append(options, crane.WithTransport(transport))
354-
}
349+
350+
opts := makeRemoteOptions(ctx, obj, transport, keychain, auth)
355351

356352
// Determine which artifact revision to pull
357-
url, err := r.getArtifactURL(obj, options)
353+
url, err := r.getArtifactURL(obj, opts.craneOpts)
358354
if err != nil {
359355
if _, ok := err.(invalidOCIURLError); ok {
360356
e := serror.NewStalling(
@@ -372,7 +368,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
372368
}
373369

374370
// Get the upstream revision from the artifact digest
375-
revision, err := r.getRevision(url, options)
371+
revision, err := r.getRevision(url, opts.craneOpts)
376372
if err != nil {
377373
e := serror.NewGeneric(
378374
fmt.Errorf("failed to determine artifact digest: %w", err),
@@ -403,7 +399,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
403399
} else if !obj.GetArtifact().HasRevision(revision) ||
404400
conditions.GetObservedGeneration(obj, sourcev1.SourceVerifiedCondition) != obj.Generation ||
405401
conditions.IsFalse(obj, sourcev1.SourceVerifiedCondition) {
406-
err := r.verifySignature(ctx, obj, url, keychain)
402+
err := r.verifySignature(ctx, obj, url, opts.verifyOpts...)
407403
if err != nil {
408404
provider := obj.Spec.Verify.Provider
409405
if obj.Spec.Verify.SecretRef == nil {
@@ -429,7 +425,7 @@ func (r *OCIRepositoryReconciler) reconcileSource(ctx context.Context, obj *sour
429425
}
430426

431427
// Pull artifact from the remote container registry
432-
img, err := crane.Pull(url, options...)
428+
img, err := crane.Pull(url, opts.craneOpts...)
433429
if err != nil {
434430
e := serror.NewGeneric(
435431
fmt.Errorf("failed to pull artifact from '%s': %w", obj.Spec.URL, err),
@@ -589,15 +585,15 @@ func (r *OCIRepositoryReconciler) digestFromRevision(revision string) string {
589585

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

596592
provider := obj.Spec.Verify.Provider
597593
switch provider {
598594
case "cosign":
599595
defaultCosignOciOpts := []soci.Options{
600-
soci.WithAuthnKeychain(keychain),
596+
soci.WithRemoteOptions(opt...),
601597
}
602598

603599
ref, err := name.ParseReference(url)
@@ -857,21 +853,6 @@ func oidcAuth(ctx context.Context, url, provider string) (authn.Authenticator, e
857853
return login.NewManager().Login(ctx, u, ref, opts)
858854
}
859855

860-
// craneOptions sets the auth headers, timeout and user agent
861-
// for all operations against remote container registries.
862-
func (r *OCIRepositoryReconciler) craneOptions(ctx context.Context, insecure bool) []crane.Option {
863-
options := []crane.Option{
864-
crane.WithContext(ctx),
865-
crane.WithUserAgent(oci.UserAgent),
866-
}
867-
868-
if insecure {
869-
options = append(options, crane.Insecure)
870-
}
871-
872-
return options
873-
}
874-
875856
// reconcileStorage ensures the current state of the storage matches the
876857
// desired and previously observed state.
877858
//
@@ -1166,3 +1147,53 @@ func (r *OCIRepositoryReconciler) calculateContentConfigChecksum(obj *sourcev1.O
11661147

11671148
return fmt.Sprintf("sha256:%x", sha256.Sum256(c))
11681149
}
1150+
1151+
// craneOptions sets the auth headers, timeout and user agent
1152+
// for all operations against remote container registries.
1153+
func craneOptions(ctx context.Context, insecure bool) []crane.Option {
1154+
options := []crane.Option{
1155+
crane.WithContext(ctx),
1156+
crane.WithUserAgent(oci.UserAgent),
1157+
}
1158+
1159+
if insecure {
1160+
options = append(options, crane.Insecure)
1161+
}
1162+
1163+
return options
1164+
}
1165+
1166+
// makeRemoteOptions returns a remoteOptions struct with the authentication and transport options set.
1167+
// The returned struct can be used to interact with a remote registry using go-containerregistry based libraries.
1168+
func makeRemoteOptions(ctxTimeout context.Context, obj *sourcev1.OCIRepository, transport http.RoundTripper,
1169+
keychain authn.Keychain, auth authn.Authenticator) remoteOptions {
1170+
o := remoteOptions{
1171+
craneOpts: craneOptions(ctxTimeout, obj.Spec.Insecure),
1172+
verifyOpts: []remote.Option{},
1173+
}
1174+
1175+
if transport != nil {
1176+
o.craneOpts = append(o.craneOpts, crane.WithTransport(transport))
1177+
o.verifyOpts = append(o.verifyOpts, remote.WithTransport(transport))
1178+
}
1179+
1180+
if auth != nil {
1181+
// auth take precedence over keychain here as we expect the caller to set
1182+
// the auth only if it is required.
1183+
o.verifyOpts = append(o.verifyOpts, remote.WithAuth(auth))
1184+
o.craneOpts = append(o.craneOpts, crane.WithAuth(auth))
1185+
return o
1186+
}
1187+
1188+
o.verifyOpts = append(o.verifyOpts, remote.WithAuthFromKeychain(keychain))
1189+
o.craneOpts = append(o.craneOpts, crane.WithAuthFromKeychain(keychain))
1190+
1191+
return o
1192+
}
1193+
1194+
// remoteOptions contains the options to interact with a remote registry.
1195+
// It can be used to pass options to go-containerregistry based libraries.
1196+
type remoteOptions struct {
1197+
craneOpts []crane.Option
1198+
verifyOpts []remote.Option
1199+
}

controllers/ocirepository_controller_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -681,7 +681,7 @@ func TestOCIRepository_reconcileSource_authStrategy(t *testing.T) {
681681
Storage: testStorage,
682682
}
683683

684-
opts := r.craneOptions(ctx, true)
684+
opts := craneOptions(ctx, true)
685685
opts = append(opts, crane.WithAuthFromKeychain(authn.DefaultKeychain))
686686
repoURL, err := r.getArtifactURL(obj, opts)
687687
g.Expect(err).To(BeNil())
@@ -1194,7 +1194,7 @@ func TestOCIRepository_reconcileSource_verifyOCISourceSignature(t *testing.T) {
11941194
g.Expect(err).ToNot(HaveOccurred())
11951195
}
11961196

1197-
opts := r.craneOptions(ctx, true)
1197+
opts := craneOptions(ctx, true)
11981198
opts = append(opts, crane.WithAuthFromKeychain(keychain))
11991199
artifactURL, err := r.getArtifactURL(obj, opts)
12001200
g.Expect(err).ToNot(HaveOccurred())
@@ -1677,7 +1677,7 @@ func TestOCIRepository_getArtifactURL(t *testing.T) {
16771677
obj.Spec.Reference = tt.reference
16781678
}
16791679

1680-
opts := r.craneOptions(ctx, true)
1680+
opts := craneOptions(ctx, true)
16811681
opts = append(opts, crane.WithAuthFromKeychain(authn.DefaultKeychain))
16821682
got, err := r.getArtifactURL(obj, opts)
16831683
if tt.wantErr {

internal/oci/verifier.go

Lines changed: 9 additions & 7 deletions
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

Lines changed: 105 additions & 0 deletions
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)