-
Notifications
You must be signed in to change notification settings - Fork 55
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
Extract config logic into own package #743
Merged
Merged
Changes from 1 commit
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
8f75915
Add new config pkg
sergiught de87857
Add tests for new config pkg
sergiught 8423370
Refactor codebase to use new config pkg
sergiught 954f34b
Minor tweaks to naming and setting path to private
sergiught b95f8bd
Add tenant validation to SetDefaultTenant
sergiught ab6bc8a
Add args validation when selecting a valid tenant from config
sergiught 7b12289
Add hint when no tenants available on tenants list
sergiught aea516e
Fix config test
sergiught 7d8d10d
Add test with keyring access token
sergiught f29bc74
Refactor root command setup
sergiught fc7f35e
Swap test order
sergiught ba5f6dd
Add tests for check tenant authentication
sergiught File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,252 @@ | ||
package config | ||
|
||
import ( | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"os" | ||
"path" | ||
"path/filepath" | ||
"sync" | ||
|
||
"github.com/google/uuid" | ||
"github.com/lestrrat-go/jwx/jwt" | ||
) | ||
|
||
// ErrConfigFileMissing is thrown when the config.json file is missing. | ||
var ErrConfigFileMissing = errors.New("config.json file is missing") | ||
|
||
// ErrNoAuthenticatedTenants is thrown when the config file has no authenticated tenants. | ||
var ErrNoAuthenticatedTenants = errors.New("Not logged in. Try `auth0 login`.") | ||
|
||
// Config holds cli configuration settings. | ||
type Config struct { | ||
onlyOnce sync.Once | ||
initError error | ||
|
||
Path string `json:"-"` | ||
|
||
InstallID string `json:"install_id,omitempty"` | ||
DefaultTenant string `json:"default_tenant"` | ||
Tenants Tenants `json:"tenants"` | ||
} | ||
|
||
// Initialize will load the config settings into memory. | ||
func (c *Config) Initialize() error { | ||
c.onlyOnce.Do(func() { | ||
c.initError = c.loadFromDisk() | ||
}) | ||
|
||
return c.initError | ||
} | ||
|
||
// VerifyAuthentication checks to see if the config is not corrupted, | ||
// and we have an authenticated tenant saved. | ||
// If we have at least one tenant saved but the DefaultTenant | ||
// is empty, it will attempt to set the first available | ||
// tenant as the DefaultTenant and save to disk. | ||
func (c *Config) VerifyAuthentication() error { | ||
if err := c.Initialize(); err != nil { | ||
return err | ||
} | ||
|
||
if len(c.Tenants) == 0 { | ||
return ErrNoAuthenticatedTenants | ||
} | ||
|
||
if c.DefaultTenant != "" { | ||
return nil | ||
} | ||
|
||
for tenant := range c.Tenants { | ||
c.DefaultTenant = tenant | ||
break // Pick first tenant and exit. | ||
} | ||
|
||
return c.saveToDisk() | ||
} | ||
|
||
// IsLoggedInWithTenant checks if we're logged in with the given tenant. | ||
func (c *Config) IsLoggedInWithTenant(tenantName string) bool { | ||
// Ignore error as we could | ||
// be not logged in yet. | ||
_ = c.Initialize() | ||
|
||
if tenantName == "" { | ||
tenantName = c.DefaultTenant | ||
} | ||
|
||
tenant, ok := c.Tenants[tenantName] | ||
if !ok { | ||
return false | ||
} | ||
|
||
token, err := jwt.ParseString(tenant.GetAccessToken()) | ||
if err != nil { | ||
return false | ||
} | ||
|
||
if err = jwt.Validate(token, jwt.WithIssuer("https://auth0.auth0.com/")); err != nil { | ||
return false | ||
} | ||
|
||
return true | ||
} | ||
|
||
// GetTenant retrieves all the tenant information from the config. | ||
func (c *Config) GetTenant(tenantName string) (Tenant, error) { | ||
if err := c.Initialize(); err != nil { | ||
return Tenant{}, err | ||
} | ||
|
||
tenant, ok := c.Tenants[tenantName] | ||
if !ok { | ||
return Tenant{}, fmt.Errorf( | ||
"failed to find tenant: %s. Run 'auth0 tenants use' to see your configured tenants "+ | ||
"or run 'auth0 login' to configure a new tenant", | ||
tenantName, | ||
) | ||
} | ||
|
||
return tenant, nil | ||
} | ||
|
||
// AddTenant adds a tenant to the config. | ||
// This is called after a login has completed. | ||
func (c *Config) AddTenant(tenant Tenant) error { | ||
// Ignore error as we could be | ||
// logging in the first time. | ||
_ = c.Initialize() | ||
|
||
c.ensureInstallIDAssigned() | ||
|
||
if c.DefaultTenant == "" { | ||
c.DefaultTenant = tenant.Domain | ||
} | ||
|
||
if c.Tenants == nil { | ||
c.Tenants = make(map[string]Tenant) | ||
} | ||
|
||
c.Tenants[tenant.Domain] = tenant | ||
|
||
return c.saveToDisk() | ||
} | ||
|
||
// RemoveTenant removes a tenant from the config. | ||
// This is called after a logout has completed. | ||
func (c *Config) RemoveTenant(tenant string) error { | ||
if err := c.Initialize(); err != nil { | ||
if errors.Is(err, ErrConfigFileMissing) { | ||
return nil // Config file is missing, so nothing to remove. | ||
} | ||
return err | ||
} | ||
|
||
if c.DefaultTenant == "" && len(c.Tenants) == 0 { | ||
return nil // Nothing to remove. | ||
} | ||
|
||
if c.DefaultTenant != "" && len(c.Tenants) == 0 { | ||
c.DefaultTenant = "" // Reset possible corruption of config file. | ||
return c.saveToDisk() | ||
} | ||
|
||
delete(c.Tenants, tenant) | ||
|
||
if c.DefaultTenant == tenant { | ||
c.DefaultTenant = "" | ||
|
||
for otherTenant := range c.Tenants { | ||
c.DefaultTenant = otherTenant | ||
break // Pick first tenant and exit as we called delete above. | ||
} | ||
} | ||
|
||
return c.saveToDisk() | ||
} | ||
|
||
// ListAllTenants retrieves a list with all configured tenants. | ||
func (c *Config) ListAllTenants() ([]Tenant, error) { | ||
if err := c.Initialize(); err != nil { | ||
return nil, err | ||
} | ||
|
||
tenants := make([]Tenant, 0, len(c.Tenants)) | ||
for _, tenant := range c.Tenants { | ||
tenants = append(tenants, tenant) | ||
} | ||
|
||
return tenants, nil | ||
} | ||
|
||
// SaveNewDefaultTenant saves the new default tenant to the disk. | ||
func (c *Config) SaveNewDefaultTenant(tenant string) error { | ||
if err := c.Initialize(); err != nil { | ||
return err | ||
} | ||
|
||
c.DefaultTenant = tenant | ||
|
||
return c.saveToDisk() | ||
} | ||
|
||
// SaveNewDefaultAppIDForTenant saves the new default app id for the tenant to the disk. | ||
func (c *Config) SaveNewDefaultAppIDForTenant(tenantName, appID string) error { | ||
tenant, err := c.GetTenant(tenantName) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
tenant.DefaultAppID = appID | ||
c.Tenants[tenant.Domain] = tenant | ||
|
||
return c.saveToDisk() | ||
} | ||
|
||
func (c *Config) ensureInstallIDAssigned() { | ||
if c.InstallID != "" { | ||
return | ||
} | ||
|
||
c.InstallID = uuid.NewString() | ||
} | ||
|
||
func (c *Config) loadFromDisk() error { | ||
if c.Path == "" { | ||
c.Path = defaultPath() | ||
} | ||
|
||
if _, err := os.Stat(c.Path); os.IsNotExist(err) { | ||
return ErrConfigFileMissing | ||
} | ||
|
||
buffer, err := os.ReadFile(c.Path) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return json.Unmarshal(buffer, c) | ||
} | ||
|
||
func (c *Config) saveToDisk() error { | ||
dir := filepath.Dir(c.Path) | ||
if _, err := os.Stat(dir); os.IsNotExist(err) { | ||
const dirPerm os.FileMode = 0700 // Directory permissions (read, write, and execute for the owner only). | ||
if err := os.MkdirAll(dir, dirPerm); err != nil { | ||
return err | ||
} | ||
} | ||
|
||
buffer, err := json.MarshalIndent(c, "", " ") | ||
if err != nil { | ||
return err | ||
} | ||
|
||
const filePerm os.FileMode = 0600 // File permissions (read and write for the owner only). | ||
return os.WriteFile(c.Path, buffer, filePerm) | ||
} | ||
|
||
func defaultPath() string { | ||
return path.Join(os.Getenv("HOME"), ".config", "auth0", "config.json") | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we expose an interface with
Config
's methods, and then use the interface in thecli
struct, so that the config can be mocked? It would be useful for testing functions that use config methods likeGetTenant()
, such as this one: https://github.com/auth0/auth0-cli/blob/main/internal/cli/apps.go#L882There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IMO it's unnecessary as right now we can simply inject an in-memory Config struct with any values we might need for testing.
So the setup to test for example the
appPickerOptions
func would be similar to:auth0-cli/internal/config/config_test.go
Lines 206 to 234 in de87857
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That involves creating an actual temp config file. But it certainly does the trick.