aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/cli/auth/zts/zts.go
blob: 19ea6e48b0ca1cf5ccb66df3cc149c0973be3858 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package zts

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"

	"github.com/vespa-engine/vespa/client/go/internal/util"
)

const (
	DefaultURL  = "https://zts.athenz.ouroath.com:4443"
	expirySlack = 5 * time.Minute
)

// Client is a client for Athenz ZTS, an authentication token service.
type Client struct {
	client   util.HTTPClient
	tokenURL *url.URL
	domain   string
	now      func() time.Time
	token    Token
	mu       sync.Mutex
}

// Token is an access token retrieved from ZTS.
type Token struct {
	Value     string
	ExpiresAt time.Time
}

func (t *Token) isExpired(now time.Time) bool { return t.ExpiresAt.Sub(now) < expirySlack }

// NewClient creates a new client for an Athenz ZTS service located at serviceURL.
func NewClient(client util.HTTPClient, domain, serviceURL string) (*Client, error) {
	tokenURL, err := url.Parse(serviceURL)
	if err != nil {
		return nil, err
	}
	tokenURL.Path = "/zts/v1/oauth2/token"
	return &Client{tokenURL: tokenURL, client: client, domain: domain, now: time.Now}, nil
}

func (c *Client) Authenticate(request *http.Request) error {
	now := c.now()
	if c.token.isExpired(now) {
		c.mu.Lock()
		if c.token.isExpired(now) {
			accessToken, err := c.AccessToken()
			if err != nil {
				c.mu.Unlock()
				return err
			}
			c.token = accessToken
		}
		c.mu.Unlock()
	}
	if request.Header == nil {
		request.Header = make(http.Header)
	}
	request.Header.Add("Authorization", "Bearer "+c.token.Value)
	return nil
}

// AccessToken returns an access token within the domain configured in client c.
func (c *Client) AccessToken() (Token, error) {
	data := fmt.Sprintf("grant_type=client_credentials&scope=%s:domain", c.domain)
	req, err := http.NewRequest("POST", c.tokenURL.String(), strings.NewReader(data))
	if err != nil {
		return Token{}, err
	}
	now := c.now()
	response, err := c.client.Do(req, 10*time.Second)
	if err != nil {
		return Token{}, err
	}
	defer response.Body.Close()
	b, err := io.ReadAll(response.Body)
	if err != nil {
		return Token{}, err
	}
	if response.StatusCode != http.StatusOK {
		body := string(b)
		if body == "" {
			body = "no body"
		}
		return Token{}, fmt.Errorf("zts: got status %d (%s) from %s", response.StatusCode, body, c.tokenURL.String())
	}
	var ztsResponse struct {
		AccessToken string `json:"access_token"`
		ExpirySecs  int    `json:"expires_in"`
	}
	if err := json.Unmarshal(b, &ztsResponse); err != nil {
		return Token{}, err
	}
	return Token{
		Value:     ztsResponse.AccessToken,
		ExpiresAt: now.Add(time.Duration(ztsResponse.ExpirySecs) * time.Second),
	}, nil
}