github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/authenticator/jwks_fetch.go (about) 1 package authenticator 2 3 import ( 4 "context" 5 "io" 6 "net/url" 7 "os" 8 "strings" 9 10 "github.com/kyma-incubator/compass/components/director/pkg/log" 11 12 "github.com/lestrrat-go/jwx/jwk" 13 "github.com/pkg/errors" 14 ) 15 16 /** 17 Copied from github.com/lestrrat-go/jwx/jwk/jwk.go & modified loading files 18 19 The MIT License (MIT) 20 21 Copyright (c) 2015 lestrrat 22 23 Permission is hereby granted, free of charge, to any person obtaining a copy 24 of this software and associated documentation files (the "Software"), to deal 25 in the Software without restriction, including without limitation the rights 26 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 27 copies of the Software, and to permit persons to whom the Software is 28 furnished to do so, subject to the following conditions: 29 30 The above copyright notice and this permission notice shall be included in all 31 copies or substantial portions of the Software. 32 33 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 34 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 35 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 36 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 37 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 38 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 39 SOFTWARE. 40 41 */ 42 43 // FetchJWK fetches a JWK resource specified by a URL 44 func FetchJWK(ctx context.Context, urlstring string, options ...jwk.FetchOption) (jwk.Set, error) { 45 u, err := url.Parse(urlstring) 46 if err != nil { 47 return nil, errors.Wrap(err, "failed to parse url") 48 } 49 50 switch u.Scheme { 51 case "http", "https": 52 return jwk.Fetch(ctx, urlstring, options...) 53 case "file": 54 filePath := strings.TrimPrefix(urlstring, "file://") 55 f, err := os.Open(filePath) 56 if err != nil { 57 return nil, errors.Wrap(err, "failed to open jwk file") 58 } 59 defer func() { 60 err := f.Close() 61 if err != nil { 62 log.C(ctx).WithError(err).Errorf("An error has occurred while closing file: %v", err) 63 } 64 }() 65 66 buf, err := io.ReadAll(f) 67 if err != nil { 68 return nil, errors.Wrap(err, "failed read content from jwk file") 69 } 70 return jwk.Parse(buf) 71 } 72 return nil, errors.Errorf("invalid url scheme %s", u.Scheme) 73 }