1 // Copyright 2019 Google LLC All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package remote 16 17 import ( 18 "context" 19 "fmt" 20 "net/http" 21 22 "github.com/google/go-containerregistry/pkg/authn" 23 "github.com/google/go-containerregistry/pkg/name" 24 "github.com/google/go-containerregistry/pkg/v1/remote/transport" 25 ) 26 27 // CheckPushPermission returns an error if the given keychain cannot authorize 28 // a push operation to the given ref. 29 // 30 // This can be useful to check whether the caller has permission to push an 31 // image before doing work to construct the image. 32 // 33 // TODO(#412): Remove the need for this method. 34 func CheckPushPermission(ref name.Reference, kc authn.Keychain, t http.RoundTripper) error { 35 auth, err := kc.Resolve(ref.Context().Registry) 36 if err != nil { 37 return fmt.Errorf("resolving authorization for %v failed: %w", ref.Context().Registry, err) 38 } 39 40 scopes := []string{ref.Scope(transport.PushScope)} 41 tr, err := transport.NewWithContext(context.TODO(), ref.Context().Registry, auth, t, scopes) 42 if err != nil { 43 return fmt.Errorf("creating push check transport for %v failed: %w", ref.Context().Registry, err) 44 } 45 // TODO(jasonhall): Against GCR, just doing the token handshake is 46 // enough, but this doesn't extend to Dockerhub 47 // (https://github.com/docker/hub-feedback/issues/1771), so we actually 48 // need to initiate an upload to tell whether the credentials can 49 // authorize a push. Figure out how to return early here when we can, 50 // to avoid a roundtrip for spec-compliant registries. 51 w := writer{ 52 repo: ref.Context(), 53 client: &http.Client{Transport: tr}, 54 } 55 loc, _, err := w.initiateUpload(context.Background(), "", "", "") 56 if loc != "" { 57 // Since we're only initiating the upload to check whether we 58 // can, we should attempt to cancel it, in case initiating 59 // reserves some resources on the server. We shouldn't wait for 60 // cancelling to complete, and we don't care if it fails. 61 go w.cancelUpload(loc) 62 } 63 return err 64 } 65 66 func (w *writer) cancelUpload(loc string) { 67 req, err := http.NewRequest(http.MethodDelete, loc, nil) 68 if err != nil { 69 return 70 } 71 _, _ = w.client.Do(req) 72 } 73