1 /* 2 * 3 * Copyright 2021 Google LLC 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * https://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 // Package tokenmanager provides tokens for authenticating to S2A. 20 package tokenmanager 21 22 import ( 23 "fmt" 24 "os" 25 26 commonpb "github.com/google/s2a-go/internal/proto/common_go_proto" 27 ) 28 29 const ( 30 s2aAccessTokenEnvironmentVariable = "S2A_ACCESS_TOKEN" 31 ) 32 33 // AccessTokenManager manages tokens for authenticating to S2A. 34 type AccessTokenManager interface { 35 // DefaultToken returns a token that an application with no specified local 36 // identity must use to authenticate to S2A. 37 DefaultToken() (token string, err error) 38 // Token returns a token that an application with local identity equal to 39 // identity must use to authenticate to S2A. 40 Token(identity *commonpb.Identity) (token string, err error) 41 } 42 43 type singleTokenAccessTokenManager struct { 44 token string 45 } 46 47 // NewSingleTokenAccessTokenManager returns a new AccessTokenManager instance 48 // that will always manage the same token. 49 // 50 // The token to be managed is read from the s2aAccessTokenEnvironmentVariable 51 // environment variable. If this environment variable is not set, then this 52 // function returns an error. 53 func NewSingleTokenAccessTokenManager() (AccessTokenManager, error) { 54 token, variableExists := os.LookupEnv(s2aAccessTokenEnvironmentVariable) 55 if !variableExists { 56 return nil, fmt.Errorf("%s environment variable is not set", s2aAccessTokenEnvironmentVariable) 57 } 58 return &singleTokenAccessTokenManager{token: token}, nil 59 } 60 61 // DefaultToken always returns the token managed by the 62 // singleTokenAccessTokenManager. 63 func (m *singleTokenAccessTokenManager) DefaultToken() (string, error) { 64 return m.token, nil 65 } 66 67 // Token always returns the token managed by the singleTokenAccessTokenManager. 68 func (m *singleTokenAccessTokenManager) Token(*commonpb.Identity) (string, error) { 69 return m.token, nil 70 } 71