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

feat: store refreshed tokens #363

Merged
merged 3 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
20 changes: 14 additions & 6 deletions cmd/cloudx/client/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
"github.com/ory/x/urlx"
)

func (h *CommandHelper) checkAuthenticated(_ context.Context) error {
func (h *CommandHelper) checkAuthenticated(ctx context.Context) error {
c, err := h.getConfig()
if err != nil {
return err
Expand All @@ -38,7 +38,11 @@ func (h *CommandHelper) checkAuthenticated(_ context.Context) error {
return ErrNotAuthenticated
}
if c.AccessToken.Expiry.Before(time.Now()) {
return ErrReauthenticate
// Do a simple call that refreshes the token. If it fails, the user should re-authenticate.
_, _, err := NewPublicOryProjectClient().OidcAPI.GetOidcUserInfo(context.WithValue(ctx, cloud.ContextOAuth2, c.TokenSource(ctx))).Execute()
if err != nil {
return ErrReauthenticate
}
}
return nil
}
Expand Down Expand Up @@ -98,7 +102,9 @@ func (h *CommandHelper) Authenticate(ctx context.Context) error {

config, err := h.getConfig()
if stderrors.Is(err, ErrNoConfig) {
config = new(Config)
config = &Config{
location: h.configLocation,
}
} else if err != nil {
return err
}
Expand All @@ -118,7 +124,9 @@ func (h *CommandHelper) Authenticate(ctx context.Context) error {
}

func (h *CommandHelper) ClearConfig() error {
return h.UpdateConfig(new(Config))
return h.UpdateConfig(&Config{
location: h.configLocation,
})
}

func oauth2ClientConfig() *oauth2.Config {
Expand Down Expand Up @@ -149,9 +157,9 @@ func (h *CommandHelper) loginOAuth2(ctx context.Context) (*Config, error) {

config := &Config{
AccessToken: token,
location: h.configLocation,
}
cl := NewPublicOryProjectClient()
userInfo, _, err := cl.OidcAPI.GetOidcUserInfo(context.WithValue(ctx, cloud.ContextOAuth2, config.TokenSource(ctx))).Execute()
userInfo, _, err := NewPublicOryProjectClient().OidcAPI.GetOidcUserInfo(context.WithValue(ctx, cloud.ContextOAuth2, config.TokenSource(ctx))).Execute()
if err != nil {
return nil, err
}
Expand Down
26 changes: 26 additions & 0 deletions cmd/cloudx/client/command_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"fmt"
"io"
"testing"
"time"

"github.com/pkg/errors"
"github.com/playwright-community/playwright-go"
Expand Down Expand Up @@ -215,6 +216,9 @@ func TestCommandHelper(t *testing.T) {
require.NoError(t, h.Authenticate(ctx))
t.Logf("authentication successful")

// we don't need playwright anymore
cleanup()

// assert success
config, err := h.GetAuthenticatedConfig(ctx)
require.NoError(t, err)
Expand All @@ -238,6 +242,28 @@ func TestCommandHelper(t *testing.T) {

assert.JSONEq(t, "[]", testhelpers.ListRelationTuples(ctx, t, defaultProject.Id).Get("relation_tuples").Raw)
t.Logf("list relation tuples request successful")

t.Run("refreshes and stores the refreshed oauth2 access token", func(t *testing.T) {
ctx := client.ContextWithOptions(ctx, client.WithOpenBrowserHook(func(uri string) error {
return fmt.Errorf("open browser hook not expected: %s", uri)
}))

oldToken := *config.AccessToken
oldToken.Expiry = time.Unix(0, 0)
oldConfig := *config
oldConfig.AccessToken = &oldToken
require.NoError(t, h.UpdateConfig(&oldConfig))

actual, err := h.GetProject(ctx, defaultProject.Id, nil)
require.NoError(t, err)
assert.Equal(t, defaultProject.Id, actual.Id)

newConfig, err := h.GetAuthenticatedConfig(ctx)
require.NoError(t, err)
require.NotNil(t, newConfig.AccessToken)
assert.NotEmpty(t, newConfig.AccessToken.AccessToken)
assert.NotEqual(t, oldToken.AccessToken, newConfig.AccessToken.AccessToken)
})
})

t.Run("func=CreateProjectAPIKey and DeleteApiKey", func(t *testing.T) {
Expand Down
51 changes: 42 additions & 9 deletions cmd/cloudx/client/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,32 @@ func getConfigPath() (string, error) {
), nil
}

func (h *CommandHelper) UpdateConfig(c *Config) error {
func (c *Config) writeUpdate() error {
c.Version = ConfigVersion
h.config = c

f, err := os.OpenFile(h.configLocation, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
f, err := os.OpenFile(c.location, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("unable to open file %q for writing: %w", h.configLocation, err)
return fmt.Errorf("unable to open file %q for writing: %w", c.location, err)
}
defer f.Close()

if err := json.NewEncoder(f).Encode(c); err != nil {
return fmt.Errorf("unable to write configuration file %q: %w", h.configLocation, err)
return fmt.Errorf("unable to write configuration file %q: %w", c.location, err)
}

return nil
}

func (h *CommandHelper) UpdateConfig(c *Config) error {
h.config = c
return c.writeUpdate()
}

func (h *CommandHelper) getOrCreateConfig() (*Config, error) {
c, err := h.getConfig()
if errors.Is(err, ErrNoConfig) {
return &Config{}, nil
return &Config{
location: h.configLocation,
}, nil
}
return c, err
}
Expand All @@ -98,7 +103,9 @@ func readConfig(location string) (*Config, error) {
}
defer f.Close()

var c Config
c := Config{
location: location,
}
if err := json.NewDecoder(f).Decode(&c); err != nil {
return nil, fmt.Errorf("unable to JSON decode the ory config file %q: %w", location, err)
}
Expand Down Expand Up @@ -158,6 +165,8 @@ type Config struct {
// isAuthenticated is a flag that we set once the session was checked and is valid.
// Because this is not stored to the config file, it means that every command execution does at most one session check.
isAuthenticated bool
// location is the path to the configuration file
location string
}

func (c *Config) ID() string {
Expand Down Expand Up @@ -195,5 +204,29 @@ type Identity struct {
}

func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource {
return oauth2ClientConfig().TokenSource(ctx, c.AccessToken)
return &autoStoreRefreshedTokenSource{
ctx: ctx,
c: c,
}
}

// autoStoreRefreshedTokenSource is a token source that automatically stores the refreshed token in the config file.
// Because it holds the context, it should not be re-used. Always create a new one using Config.TokenSource() with the current context.
type autoStoreRefreshedTokenSource struct {
ctx context.Context
c *Config
}

func (s *autoStoreRefreshedTokenSource) Token() (*oauth2.Token, error) {
newToken, err := oauth2ClientConfig().TokenSource(s.ctx, s.c.AccessToken).Token()
if err != nil {
return nil, err
}
if newToken.AccessToken != s.c.AccessToken.AccessToken {
s.c.AccessToken = newToken
if err := s.c.writeUpdate(); err != nil {
return nil, err
}
}
return newToken, nil
}
7 changes: 6 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"fmt"
"os"
"sync"

"github.com/pkg/errors"
"github.com/spf13/cobra"
Expand All @@ -18,6 +19,8 @@ import (
"github.com/ory/x/cmdx"
)

var commandTemplatingOnce sync.Once

func NewRootCmd() *cobra.Command {
c := &cobra.Command{
Use: "ory",
Expand Down Expand Up @@ -48,7 +51,9 @@ func NewRootCmd() *cobra.Command {
cloudx.NewIsCmd(),
versionCmd,
)
cmdx.EnableUsageTemplating(c)
commandTemplatingOnce.Do(func() {
cmdx.EnableUsageTemplating(c)
})

return c
}
Expand Down
Loading