zero/api: reset token and url cache if 401 is received (#5256)

zero/api: reset token cache if 401 is received
This commit is contained in:
Denis Mishin 2024-09-03 15:40:28 -04:00 committed by GitHub
parent a04d1a450c
commit ce12e51cf5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 91 additions and 32 deletions

View file

@ -17,18 +17,23 @@ const (
var userAgent = version.UserAgent()
type client struct {
tokenProvider TokenProviderFn
tokenProvider TokenCache
httpClient *http.Client
minTokenTTL time.Duration
}
// TokenProviderFn is a function that returns a token that is expected to be valid for at least minTTL
type TokenProviderFn func(ctx context.Context, minTTL time.Duration) (string, error)
// TokenCache interface for fetching and caching tokens
type TokenCache interface {
// GetToken returns a token that is expected to be valid for at least minTTL duration
GetToken(ctx context.Context, minTTL time.Duration) (string, error)
// Reset resets the token cache
Reset()
}
// NewAuthorizedClient creates a new HTTP client that will automatically add an authorization header
func NewAuthorizedClient(
endpoint string,
tokenProvider TokenProviderFn,
tokenProvider TokenCache,
httpClient *http.Client,
) (ClientWithResponsesInterface, error) {
c := &client{
@ -43,12 +48,21 @@ func NewAuthorizedClient(
func (c *client) Do(req *http.Request) (*http.Response, error) {
ctx := req.Context()
token, err := c.tokenProvider(ctx, c.minTokenTTL)
token, err := c.tokenProvider.GetToken(ctx, c.minTokenTTL)
if err != nil {
return nil, fmt.Errorf("error getting token: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("User-Agent", userAgent)
return c.httpClient.Do(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusUnauthorized {
c.tokenProvider.Reset()
}
return resp, nil
}