tokenmanager.go

 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.
20package tokenmanager
21
22import (
23	"fmt"
24	"os"
25
26	commonpbv1 "github.com/google/s2a-go/internal/proto/common_go_proto"
27	commonpb "github.com/google/s2a-go/internal/proto/v2/common_go_proto"
28)
29
30const (
31	s2aAccessTokenEnvironmentVariable = "S2A_ACCESS_TOKEN"
32)
33
34// AccessTokenManager manages tokens for authenticating to S2A.
35type AccessTokenManager interface {
36	// DefaultToken returns a token that an application with no specified local
37	// identity must use to authenticate to S2A.
38	DefaultToken() (token string, err error)
39	// Token returns a token that an application with local identity equal to
40	// identity must use to authenticate to S2A.
41	Token(identity interface{}) (token string, err error)
42}
43
44type singleTokenAccessTokenManager struct {
45	token string
46}
47
48// NewSingleTokenAccessTokenManager returns a new AccessTokenManager instance
49// that will always manage the same token.
50//
51// The token to be managed is read from the s2aAccessTokenEnvironmentVariable
52// environment variable. If this environment variable is not set, then this
53// function returns an error.
54func NewSingleTokenAccessTokenManager() (AccessTokenManager, error) {
55	token, variableExists := os.LookupEnv(s2aAccessTokenEnvironmentVariable)
56	if !variableExists {
57		return nil, fmt.Errorf("%s environment variable is not set", s2aAccessTokenEnvironmentVariable)
58	}
59	return &singleTokenAccessTokenManager{token: token}, nil
60}
61
62// DefaultToken always returns the token managed by the
63// singleTokenAccessTokenManager.
64func (m *singleTokenAccessTokenManager) DefaultToken() (string, error) {
65	return m.token, nil
66}
67
68// Token always returns the token managed by the singleTokenAccessTokenManager.
69func (m *singleTokenAccessTokenManager) Token(identity interface{}) (string, error) {
70	switch v := identity.(type) {
71	case *commonpbv1.Identity:
72		// valid type.
73	case *commonpb.Identity:
74		// valid type.
75	default:
76		return "", fmt.Errorf("Incorrect identity type: %v", v)
77	}
78	return m.token, nil
79}