github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/auth/service_account_token_provider.go (about) 1 /* 2 * Copyright 2020 The Compass 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 auth 18 19 import ( 20 "context" 21 "os" 22 23 "github.com/pkg/errors" 24 ) 25 26 // DefaultServiceAccountTokenPath missing godoc 27 const DefaultServiceAccountTokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" 28 29 // serviceAccountTokenAuthorizationProvider presents an AuthorizationProvider implementation which uses K8S Service Account tokens for the Authorization header 30 type serviceAccountTokenAuthorizationProvider struct { 31 path string 32 } 33 34 // NewServiceAccountTokenAuthorizationProvider constructs an serviceAccountTokenAuthorizationProvider 35 func NewServiceAccountTokenAuthorizationProvider() *serviceAccountTokenAuthorizationProvider { 36 return &serviceAccountTokenAuthorizationProvider{} 37 } 38 39 // NewServiceAccountTokenAuthorizationProviderWithPath constructs an serviceAccountTokenAuthorizationProvider with a given path 40 func NewServiceAccountTokenAuthorizationProviderWithPath(path string) *serviceAccountTokenAuthorizationProvider { 41 return &serviceAccountTokenAuthorizationProvider{ 42 path: path, 43 } 44 } 45 46 // Name specifies the name of the AuthorizationProvider 47 func (u serviceAccountTokenAuthorizationProvider) Name() string { 48 return "ServiceAccountTokenAuthorizationProvider" 49 } 50 51 // Matches contains the logic for matching the AuthorizationProvider 52 func (u serviceAccountTokenAuthorizationProvider) Matches(ctx context.Context) bool { 53 _, err := LoadFromContext(ctx) 54 return err != nil 55 } 56 57 // GetAuthorization reads pod's service account token from the filesystem 58 func (u serviceAccountTokenAuthorizationProvider) GetAuthorization(_ context.Context) (string, error) { 59 path := u.path 60 if len(path) == 0 { 61 path = DefaultServiceAccountTokenPath 62 } 63 data, err := os.ReadFile(path) 64 if err != nil { 65 return "", errors.Wrapf(err, "Unable to read service account token file") 66 } 67 68 return "Bearer " + string(data), nil 69 }