Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup token refresh system based on token expiry #30

Merged
merged 2 commits into from
Aug 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ require (
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/bmatcuk/doublestar/v4 v4.6.1 // indirect
github.com/cloudflare/circl v1.3.7 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible
ryanhristovski marked this conversation as resolved.
Show resolved Hide resolved
github.com/fatih/color v1.17.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/go-cmp v0.6.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ github.com/cyphar/filepath-securejoin v0.2.4/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxG
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
Expand Down
82 changes: 61 additions & 21 deletions internal/pkg/hubclient/client.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// API client for hub.docker.com
package hubclient

import (
Expand All @@ -9,7 +8,10 @@ import (
"fmt"
"io"
"net/http"
"sync"
"time"

"github.com/dgrijalva/jwt-go"
)

type Auth struct {
Expand All @@ -22,10 +24,13 @@ type Token struct {
}

type Client struct {
BaseURL string
auth Auth
HTTPClient *http.Client
userAgent string
BaseURL string
auth Auth
HTTPClient *http.Client
userAgent string
token string
tokenExpiry time.Time
mu sync.Mutex
}

type Config struct {
Expand All @@ -35,7 +40,6 @@ type Config struct {
UserAgentVersion string
}

// Create the API client, providing the authentication.
func NewClient(config Config) *Client {
version := config.UserAgentVersion
if version == "" {
Expand All @@ -55,51 +59,87 @@ func NewClient(config Config) *Client {
}
}

func (c *Client) sendRequest(ctx context.Context, method string, url string, body []byte, result interface{}) error {
// parseTokenExpiration parses the JWT token to get the exact expiration time.
func parseTokenExpiration(tokenString string) (time.Time, error) {
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
return time.Time{}, err
}

if claims, ok := token.Claims.(jwt.MapClaims); ok {
if exp, ok := claims["exp"].(float64); ok {
return time.Unix(int64(exp), 0), nil
}
}

return time.Time{}, fmt.Errorf("could not find expiration in token")
}

func (c *Client) ensureValidToken(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()

if c.token != "" && time.Now().Before(c.tokenExpiry) {
return nil
}

authJSON, err := json.Marshal(c.auth)
if err != nil {
return err
}

req, err := http.NewRequest("POST", fmt.Sprintf("%s/users/login/", c.BaseURL), bytes.NewBuffer(authJSON))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")

req.Header.Set("Content-Type", "application/json")
req = req.WithContext(ctx)

res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}

defer res.Body.Close()

if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
bodyBytes, readErr := io.ReadAll(res.Body)
if readErr != nil {
return readErr
}
return errors.New(string(bodyBytes))
return fmt.Errorf("HTTP error: %s", res.Status)
}

token := Token{}
if err = json.NewDecoder(res.Body).Decode(&token); err != nil {
return err
}

req, err = http.NewRequest(method, fmt.Sprintf("%s%s", c.BaseURL, url), bytes.NewBuffer(body))
// Parse the exact expiration time from the token
expirationTime, err := parseTokenExpiration(token.Token)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")

// Store the new token and its exact expiration time
c.token = token.Token
c.tokenExpiry = expirationTime

return nil
}

func (c *Client) sendRequest(ctx context.Context, method string, url string, body []byte, result interface{}) error {
if err := c.ensureValidToken(ctx); err != nil {
return err
}

req, err := http.NewRequest(method, fmt.Sprintf("%s%s", c.BaseURL, url), bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.Token))
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token))

req = req.WithContext(ctx)

res, err = c.HTTPClient.Do(req)
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
Expand Down