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

Extract config logic into own package #743

Merged
merged 12 commits into from
Apr 19, 2023
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ require (
github.com/stretchr/testify v1.8.2
github.com/tidwall/pretty v1.2.1
github.com/zalando/go-keyring v0.2.2
golang.org/x/exp v0.0.0-20230321023759-10a507213a29
golang.org/x/oauth2 v0.7.0
golang.org/x/sync v0.1.0
golang.org/x/sys v0.7.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
Expand Down
252 changes: 252 additions & 0 deletions internal/config/config.go
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 {
Copy link
Contributor

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 the cli struct, so that the config can be mocked? It would be useful for testing functions that use config methods like GetTenant(), such as this one: https://github.com/auth0/auth0-cli/blob/main/internal/cli/apps.go#L882

Copy link
Contributor Author

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:

tempFile := createTempConfigFile(t, []byte(`
{
"install_id": "3998b053-dd7f-4bfe-bb10-c4f3a96a0180",
"default_tenant": "auth0-cli.eu.auth0.com",
"tenants": {
"auth0-cli.eu.auth0.com": {
"name": "auth0-cli",
"domain": "auth0-cli.eu.auth0.com",
"access_token": "eyfSaswe",
"expires_at": "2023-04-18T11:18:07.998809Z",
"client_id": "secret"
}
}
}
`))
expectedTenant := Tenant{
Name: "auth0-cli",
Domain: "auth0-cli.eu.auth0.com",
AccessToken: "eyfSaswe",
ExpiresAt: time.Date(2023, time.April, 18, 11, 18, 7, 998809000, time.UTC),
ClientID: "secret",
}
config := &Config{Path: tempFile}
actualTenant, err := config.GetTenant("auth0-cli.eu.auth0.com")
assert.NoError(t, err)
assert.Equal(t, expectedTenant, actualTenant)

Copy link
Contributor

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.

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")
}
Loading