diff --git a/cliext/config.go b/cliext/config.go new file mode 100644 index 000000000..9f960af6b --- /dev/null +++ b/cliext/config.go @@ -0,0 +1,277 @@ +package cliext + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "time" + + "github.com/BurntSushi/toml" + "go.temporal.io/sdk/contrib/envconfig" +) + +type ClientConfig struct { + Profiles map[string]*Profile +} + +type LoadConfigOptions struct { + // Override the file path to use to load the TOML file for config. Defaults to TEMPORAL_CONFIG_FILE environment + // variable or if that is unset/empty, defaults to [os.UserConfigDir]/temporal/temporal.toml. If ConfigFileData is + // set, this cannot be set and no file loading from disk occurs. Ignored if DisableFile is true. + ConfigFilePath string + // Override the environment variable lookup. If nil, defaults to [EnvLookupOS]. + EnvLookup envconfig.EnvLookup +} + +type LoadConfigResult struct { + // Config is the loaded configuration with its profiles. + Config ClientConfig + // ConfigFilePath is the resolved path to the configuration file that was loaded. + // This may differ from the input if TEMPORAL_CONFIG_FILE env var was used. + ConfigFilePath string +} + +// oauthConfigTOML is the TOML representation of OAuthConfig. +type oauthConfigTOML struct { + ClientID string `toml:"client_id,omitempty"` + ClientSecret string `toml:"client_secret,omitempty"` + TokenURL string `toml:"token_url,omitempty"` + AuthURL string `toml:"auth_url,omitempty"` + AccessToken string `toml:"access_token,omitempty"` + RefreshToken string `toml:"refresh_token,omitempty"` + TokenType string `toml:"token_type,omitempty"` + ExpiresAt string `toml:"expires_at,omitempty"` + Scopes []string `toml:"scopes,omitempty"` + RequestParams inlineStringMap `toml:"request_params,omitempty"` +} + +type rawProfileWithOAuth struct { + OAuth *oauthConfigTOML `toml:"oauth"` +} + +type rawConfigWithOAuth struct { + Profile map[string]*rawProfileWithOAuth `toml:"profile"` +} + +// LoadConfig loads the client configuration from the specified file or default location. +// If ConfigFilePath is empty, the TEMPORAL_CONFIG_FILE environment variable is checked, +// then the default path is used. +func LoadConfig(options LoadConfigOptions) (LoadConfigResult, error) { + envLookup := options.EnvLookup + if envLookup == nil { + envLookup = envconfig.EnvLookupOS + } + + // Resolve the config file path. + resolvedPath := options.ConfigFilePath + if resolvedPath == "" { + resolvedPath, _ = envLookup.LookupEnv("TEMPORAL_CONFIG_FILE") + } + if resolvedPath == "" { + var err error + resolvedPath, err = envconfig.DefaultConfigFilePath() + if err != nil { + return LoadConfigResult{}, fmt.Errorf("failed to get default config path: %w", err) + } + } + + clientConfig, err := envconfig.LoadClientConfig(envconfig.LoadClientConfigOptions{ + ConfigFilePath: resolvedPath, + EnvLookup: envLookup, + }) + if err != nil { + return LoadConfigResult{}, err + } + + // Load OAuth for all profiles by parsing the config file directly. + oauthByProfile, err := loadOAuthConfigFromFile(resolvedPath) + if err != nil { + return LoadConfigResult{}, err + } + + // Merge profiles and their OAuth configurations. + profiles := make(map[string]*Profile) + for name, baseProfile := range clientConfig.Profiles { + profiles[name] = &Profile{ + ClientConfigProfile: *baseProfile, + OAuth: oauthByProfile[name], + } + } + + return LoadConfigResult{ + Config: ClientConfig{Profiles: profiles}, + ConfigFilePath: resolvedPath, + }, nil +} + +func loadOAuthConfigFromFile(path string) (map[string]*OAuthConfig, error) { + data, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + return nil, fmt.Errorf("failed to read config file: %w", err) + } + + var raw rawConfigWithOAuth + if _, err := toml.Decode(string(data), &raw); err != nil { + return nil, fmt.Errorf("failed to parse config file: %w", err) + } + + oauthByProfile := make(map[string]*OAuthConfig) + for profileName, profile := range raw.Profile { + if profile == nil || profile.OAuth == nil { + oauthByProfile[profileName] = nil + continue + } + cfg := profile.OAuth + oauth := &OAuthConfig{ + OAuthClientConfig: OAuthClientConfig{ + ClientID: cfg.ClientID, + ClientSecret: cfg.ClientSecret, + TokenURL: cfg.TokenURL, + AuthURL: cfg.AuthURL, + RequestParams: cfg.RequestParams, + Scopes: cfg.Scopes, + }, + OAuthToken: OAuthToken{ + AccessToken: cfg.AccessToken, + RefreshToken: cfg.RefreshToken, + TokenType: cfg.TokenType, + }, + } + if cfg.ExpiresAt != "" { + t, err := time.Parse(time.RFC3339, cfg.ExpiresAt) + if err != nil { + return nil, fmt.Errorf("failed to parse expires_at for profile %q: %w", profileName, err) + } + oauth.AccessTokenExpiresAt = t + } + oauthByProfile[profileName] = oauth + } + return oauthByProfile, nil +} + +type WriteConfigOptions struct { + // Config is the configuration to write. + Config ClientConfig + // ConfigFilePath is the path to write the configuration file to. + // If empty, TEMPORAL_CONFIG_FILE env var is checked, then the default path is used. + ConfigFilePath string + // Override the environment variable lookup. If nil, defaults to [EnvLookupOS]. + EnvLookup envconfig.EnvLookup +} + +// ConfigToTOML serializes the configuration to TOML bytes. +func ConfigToTOML(config *ClientConfig) ([]byte, error) { + // Build envconfig.ClientConfig from profiles. + envConfig := &envconfig.ClientConfig{ + Profiles: make(map[string]*envconfig.ClientConfigProfile), + } + for name, p := range config.Profiles { + if p != nil { + envConfig.Profiles[name] = &p.ClientConfigProfile + } + } + + // Convert base config to TOML. + b, err := envConfig.ToTOML(envconfig.ClientConfigToTOMLOptions{}) + if err != nil { + return nil, fmt.Errorf("failed building TOML: %w", err) + } + + // Append OAuth sections per profile. + var buf bytes.Buffer + buf.Write(b) + + for name, profile := range config.Profiles { + if profile == nil || profile.OAuth == nil { + continue + } + oauthTOML := &oauthConfigTOML{ + ClientID: profile.OAuth.ClientID, + ClientSecret: profile.OAuth.ClientSecret, + TokenURL: profile.OAuth.TokenURL, + AuthURL: profile.OAuth.AuthURL, + AccessToken: profile.OAuth.AccessToken, + RefreshToken: profile.OAuth.RefreshToken, + TokenType: profile.OAuth.TokenType, + Scopes: profile.OAuth.Scopes, + RequestParams: profile.OAuth.RequestParams, + } + if !profile.OAuth.AccessTokenExpiresAt.IsZero() { + oauthTOML.ExpiresAt = profile.OAuth.AccessTokenExpiresAt.Format(time.RFC3339) + } + + oauthBytes, err := toml.Marshal(oauthTOML) + if err != nil { + return nil, fmt.Errorf("failed marshaling OAuth config: %w", err) + } + fmt.Fprintf(&buf, "\n[profile.%s.oauth]\n", name) + buf.Write(oauthBytes) + } + return buf.Bytes(), nil +} + +// WriteConfig writes the environment configuration to disk. +func WriteConfig(opts WriteConfigOptions) error { + envLookup := opts.EnvLookup + if envLookup == nil { + envLookup = envconfig.EnvLookupOS + } + + configFilePath := opts.ConfigFilePath + if configFilePath == "" { + configFilePath, _ = envLookup.LookupEnv("TEMPORAL_CONFIG_FILE") + if configFilePath == "" { + var err error + if configFilePath, err = envconfig.DefaultConfigFilePath(); err != nil { + return err + } + } + } + + b, err := ConfigToTOML(&opts.Config) + if err != nil { + return err + } + + // Write to file, making dirs as needed. + if err := os.MkdirAll(filepath.Dir(configFilePath), 0700); err != nil { + return fmt.Errorf("failed making config file parent dirs: %w", err) + } + if err := os.WriteFile(configFilePath, b, 0600); err != nil { + return fmt.Errorf("failed writing config file: %w", err) + } + return nil +} + +// inlineStringMap wraps a map to marshal as an inline TOML table. +type inlineStringMap map[string]string + +func (m inlineStringMap) MarshalTOML() ([]byte, error) { + if len(m) == 0 { + return nil, nil + } + + // Sort keys for deterministic output. + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + + var buf bytes.Buffer + buf.WriteString("{ ") + for i, k := range keys { + if i > 0 { + buf.WriteString(", ") + } + fmt.Fprintf(&buf, "%s = %q", k, m[k]) + } + buf.WriteString(" }") + return buf.Bytes(), nil +} diff --git a/internal/devserver/freeport.go b/cliext/freeport.go similarity index 92% rename from internal/devserver/freeport.go rename to cliext/freeport.go index 8cd89081f..d8c98f358 100644 --- a/internal/devserver/freeport.go +++ b/cliext/freeport.go @@ -1,4 +1,4 @@ -package devserver +package cliext import ( "fmt" @@ -24,13 +24,13 @@ func GetFreePort(host string) (int, error) { host = MaybeEscapeIPv6(host) l, err := net.Listen("tcp", host+":0") if err != nil { - return 0, fmt.Errorf("failed to assign a free port: %v", err) + return 0, fmt.Errorf("failed to assign a free port: %w", err) } defer l.Close() port := l.Addr().(*net.TCPAddr).Port // On Linux and some BSD variants, ephemeral ports are randomized, and may - // consequently repeat within a short time frame after the listenning end + // consequently repeat within a short time frame after the listening end // has been closed. To avoid this, we make a connection to the port, then // close that connection from the server's side (this is very important), // which puts the connection in TIME_WAIT state for some time (by default, @@ -50,17 +50,17 @@ func GetFreePort(host string) (int, error) { // to ::1). For safety, rebuild address form the original host instead. tcpAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { - return 0, fmt.Errorf("error resolving address: %v", err) + return 0, fmt.Errorf("error resolving address: %w", err) } r, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { - return 0, fmt.Errorf("failed to assign a free port: %v", err) + return 0, fmt.Errorf("failed to assign a free port: %w", err) } c, err := l.Accept() if err != nil { - return 0, fmt.Errorf("failed to assign a free port: %v", err) + return 0, fmt.Errorf("failed to assign a free port: %w", err) } - // Closing the socket from the server side + // Closing the socket from the server side. c.Close() defer r.Close() } diff --git a/internal/devserver/freeport_test.go b/cliext/freeport_test.go similarity index 85% rename from internal/devserver/freeport_test.go rename to cliext/freeport_test.go index 5839cef65..27bb3f12a 100644 --- a/internal/devserver/freeport_test.go +++ b/cliext/freeport_test.go @@ -1,18 +1,18 @@ -package devserver_test +package cliext_test import ( "fmt" "net" "testing" - "github.com/temporalio/cli/internal/devserver" + "github.com/temporalio/cli/cliext" ) func TestFreePort_NoDouble(t *testing.T) { host := "127.0.0.1" portSet := make(map[int]bool) for i := 0; i < 2000; i++ { - p, err := devserver.GetFreePort(host) + p, err := cliext.GetFreePort(host) if err != nil { t.Fatalf("Error: %s", err) break @@ -30,7 +30,7 @@ func TestFreePort_NoDouble(t *testing.T) { func TestFreePort_CanBindImmediatelySameProcess(t *testing.T) { host := "127.0.0.1" for i := 0; i < 500; i++ { - p, err := devserver.GetFreePort(host) + p, err := cliext.GetFreePort(host) if err != nil { t.Fatalf("Error: %s", err) break @@ -45,7 +45,7 @@ func TestFreePort_CanBindImmediatelySameProcess(t *testing.T) { func TestFreePort_IPv4Unspecified(t *testing.T) { host := "0.0.0.0" - p, err := devserver.GetFreePort(host) + p, err := cliext.GetFreePort(host) if err != nil { t.Fatalf("Error: %s", err) return @@ -59,7 +59,7 @@ func TestFreePort_IPv4Unspecified(t *testing.T) { func TestFreePort_IPv6Unspecified(t *testing.T) { host := "::" - p, err := devserver.GetFreePort(host) + p, err := cliext.GetFreePort(host) if err != nil { t.Fatalf("Error: %s", err) return @@ -72,8 +72,9 @@ func TestFreePort_IPv6Unspecified(t *testing.T) { } // This function is used as part of unit tests, to ensure that the port +// is available for listening and dialing. func tryListenAndDialOn(host string, port int) error { - host = devserver.MaybeEscapeIPv6(host) + host = cliext.MaybeEscapeIPv6(host) l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { return err diff --git a/cliext/go.mod b/cliext/go.mod new file mode 100644 index 000000000..5d24f7646 --- /dev/null +++ b/cliext/go.mod @@ -0,0 +1,39 @@ +module github.com/temporalio/cli/cliext + +go 1.25.0 + +require ( + github.com/BurntSushi/toml v1.4.0 + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c + github.com/stretchr/testify v1.10.0 + go.temporal.io/sdk/contrib/envconfig v0.1.0 + golang.org/x/oauth2 v0.33.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/mock v1.6.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 // indirect + github.com/nexus-rpc/sdk-go v0.3.0 // indirect + github.com/pborman/uuid v1.2.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/robfig/cron v1.2.0 // indirect + github.com/stretchr/objx v0.5.2 // indirect + go.temporal.io/api v1.44.1 // indirect + go.temporal.io/sdk v1.32.1 // indirect + golang.org/x/exp v0.0.0-20231127185646-65229373498e // indirect + golang.org/x/net v0.28.0 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.24.0 // indirect + golang.org/x/text v0.17.0 // indirect + golang.org/x/time v0.3.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20240827150818-7e3bb234dfed // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed // indirect + google.golang.org/grpc v1.66.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/cliext/go.sum b/cliext/go.sum new file mode 100644 index 000000000..6e43657a4 --- /dev/null +++ b/cliext/go.sum @@ -0,0 +1,188 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= +github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +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/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a h1:yDWHCSQ40h88yih2JAcL6Ls/kVkSE8GFACTGVnMPruw= +github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a/go.mod h1:7Ga40egUymuWXxAe151lTNnCv97MddSOVsjpPPkityA= +github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.5.0 h1:LUVKkCeviFUMKqHa4tXIIij/lbhnMbP7Fn5wKdKkRh4= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= +github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjwqUPTYmYuemVOx+Ys= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/nexus-rpc/sdk-go v0.3.0 h1:Y3B0kLYbMhd4C2u00kcYajvmOrfozEtTV/nHSnV57jA= +github.com/nexus-rpc/sdk-go v0.3.0/go.mod h1:TpfkM2Cw0Rlk9drGkoiSMpFqflKTiQLWUNyKJjF8mKQ= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/pborman/uuid v1.2.1 h1:+ZZIw58t/ozdjRaXh/3awHfmWRbzYxJoAdNJxe/3pvw= +github.com/pborman/uuid v1.2.1/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ= +github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.temporal.io/api v1.44.1 h1:sb5Hq08AB0WtYvfLJMiWmHzxjqs2b+6Jmzg4c8IOeng= +go.temporal.io/api v1.44.1/go.mod h1:1WwYUMo6lao8yl0371xWUm13paHExN5ATYT/B7QtFis= +go.temporal.io/sdk v1.32.1 h1:slA8prhdFr4lxpsTcRusWVitD/cGjELfKUh0mBj73SU= +go.temporal.io/sdk v1.32.1/go.mod h1:8U8H7rF9u4Hyb4Ry9yiEls5716DHPNvVITPNkgWUwE8= +go.temporal.io/sdk/contrib/envconfig v0.1.0 h1:s+G/Ujph+Xl2jzLiiIm2T1vuijDkUL4Kse49dgDVGBE= +go.temporal.io/sdk/contrib/envconfig v0.1.0/go.mod h1:FQEO3C56h9C7M6sDgSanB8HnBTmopw9qgVx4F1S6pJk= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20231127185646-65229373498e h1:Gvh4YaCaXNs6dKTlfgismwWZKyjVZXwOPfIyUaqU3No= +golang.org/x/exp v0.0.0-20231127185646-65229373498e/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo= +golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= +golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto/googleapis/api v0.0.0-20240827150818-7e3bb234dfed h1:3RgNmBoI9MZhsj3QxC+AP/qQhNwpCLOvYDYYsFrhFt0= +google.golang.org/genproto/googleapis/api v0.0.0-20240827150818-7e3bb234dfed/go.mod h1:OCdP9MfskevB/rbYvHTsXTtKC+3bHWajPdoKgjcYkfo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed h1:J6izYgfBXAI3xTKLgxzTmUltdYaLsuBxFCgDHWJ/eXg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.66.0 h1:DibZuoBznOxbDQxRINckZcUvnCEvrW9pcWIE2yF9r1c= +google.golang.org/grpc v1.66.0/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/cliext/oauth.go b/cliext/oauth.go new file mode 100644 index 000000000..801273e40 --- /dev/null +++ b/cliext/oauth.go @@ -0,0 +1,244 @@ +package cliext + +import ( + "context" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "net" + "net/http" + "sync" + "time" + + "github.com/pkg/browser" + "golang.org/x/oauth2" +) + +type OAuthClientConfig struct { + // ClientID is the OAuth client ID. + ClientID string + // ClientSecret is the OAuth client secret. + ClientSecret string + // TokenURL is the OAuth token endpoint URL. + TokenURL string + // AuthURL is the OAuth authorization endpoint URL. + AuthURL string + // Scopes are the requested OAuth scopes. + Scopes []string + // RequestParams are additional parameters to include in OAuth requests. + RequestParams map[string]string +} + +type OAuthToken struct { + // AccessToken is the current access token. + AccessToken string + // AccessTokenExpiresAt is when the access token expires. + AccessTokenExpiresAt time.Time + // AccessTokenRefreshed indicates whether the access token was just refreshed. + AccessTokenRefreshed bool + // RefreshToken is the refresh token for obtaining new access tokens. + RefreshToken string + // TokenType is the type of token (usually "Bearer"). + TokenType string +} + +type OAuthConfig struct { + OAuthClientConfig + OAuthToken +} + +func oauthTokenFromOAuth2(token *oauth2.Token) OAuthToken { + return OAuthToken{ + AccessToken: token.AccessToken, + AccessTokenExpiresAt: token.Expiry, + RefreshToken: token.RefreshToken, + TokenType: token.TokenType, + } +} + +// OAuthClient handles OAuth authentication using the Authorization Code Flow. +// See https://tools.ietf.org/html/rfc6749#section-4.1 for details. +type OAuthClient struct { + Options OAuthClientConfig + // OnAuthURL is called with the authorization URL. If nil, the URL is opened in the browser. + // This can be set to override the default behavior, e.g., for testing. + OnAuthURL func(authURL string) +} + +func NewOAuthClient(opts OAuthClientConfig) *OAuthClient { + return &OAuthClient{Options: opts} +} + +func (c *OAuthClient) createOAuth2Config(redirectURL string) *oauth2.Config { + return &oauth2.Config{ + ClientID: c.Options.ClientID, + ClientSecret: c.Options.ClientSecret, + RedirectURL: redirectURL, + Endpoint: oauth2.Endpoint{ + AuthURL: c.Options.AuthURL, + TokenURL: c.Options.TokenURL, + }, + Scopes: c.Options.Scopes, + } +} + +type oauthCallbackResult struct { + code string + err error +} + +// Login performs the OAuth Authorization Code Flow with PKCE (Proof Key for Code Exchange). +// +// It starts a local HTTP server to receive the callback, generates an authorization URL, +// and exchanges the authorization code for a token. +func (c *OAuthClient) Login(ctx context.Context) (OAuthToken, error) { + // Get a free port and start callback listener + port, err := GetFreePort("127.0.0.1") + if err != nil { + return OAuthToken{}, fmt.Errorf("failed to get free port: %w", err) + } + listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + return OAuthToken{}, fmt.Errorf("failed to start callback server: %w", err) + } + defer listener.Close() + + // Generate PKCE challenge. + verifier := oauth2.GenerateVerifier() + authOpts := []oauth2.AuthCodeOption{ + oauth2.S256ChallengeOption(verifier), + } + + // Add any additional request parameters. + for key, value := range c.Options.RequestParams { + authOpts = append(authOpts, oauth2.SetAuthURLParam(key, value)) + } + + // Generate random state for CSRF protection. + var stateBytes [16]byte + if _, err := rand.Read(stateBytes[:]); err != nil { + return OAuthToken{}, fmt.Errorf("failed to generate state: %w", err) + } + state := base64.RawURLEncoding.EncodeToString(stateBytes[:]) + + // Generate authorization URL. + redirectURL := fmt.Sprintf("http://127.0.0.1:%d/callback", port) + cfg := c.createOAuth2Config(redirectURL) + authURL := cfg.AuthCodeURL(state, authOpts...) + + // Handle auth URL notification. + if c.OnAuthURL != nil { + c.OnAuthURL(authURL) + } else { + fmt.Printf("Opening browser to authorize. If it doesn't open, visit: %s\n", authURL) + _ = browser.OpenURL(authURL) + } + + // Start HTTP server to handle callback. + var once sync.Once + resultCh := make(chan oauthCallbackResult, 1) + server := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/callback" { + http.NotFound(w, r) + return + } + + // Use sync.Once to only process the first callback. + once.Do(func() { + query := r.URL.Query() + + // Check for OAuth error response. + if errCode := query.Get("error"); errCode != "" { + errDesc := query.Get("error_description") + if errDesc == "" { + errDesc = errCode + } + resultCh <- oauthCallbackResult{err: fmt.Errorf("authorization failed: %s", errDesc)} + http.Error(w, fmt.Sprintf("Authorization failed: %s", errDesc), http.StatusBadRequest) + return + } + + // Validate state to prevent CSRF. + if query.Get("state") != state { + resultCh <- oauthCallbackResult{err: fmt.Errorf("invalid state parameter")} + http.Error(w, "Invalid state parameter", http.StatusBadRequest) + return + } + + // Check for authorization code. + code := query.Get("code") + if code == "" { + resultCh <- oauthCallbackResult{err: fmt.Errorf("missing authorization code")} + http.Error(w, "Missing authorization code", http.StatusBadRequest) + return + } + + resultCh <- oauthCallbackResult{code: code} + fmt.Fprint(w, "Authorization successful! You can close this window.") + }) + }), + } + go server.Serve(listener) + defer func() { + shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + server.Shutdown(shutdownCtx) + }() + + // Wait for callback result or context cancellation. + var result oauthCallbackResult + select { + case result = <-resultCh: + case <-ctx.Done(): + return OAuthToken{}, ctx.Err() + } + if result.err != nil { + return OAuthToken{}, result.err + } + + // Exchange code for token with PKCE verifier. + token, err := cfg.Exchange(ctx, result.code, oauth2.VerifierOption(verifier)) + if err != nil { + return OAuthToken{}, fmt.Errorf("failed to exchange code for token: %w", err) + } + + return oauthTokenFromOAuth2(token), nil +} + +// Token returns a valid access token, refreshing if necessary. +func (c *OAuthClient) Token(ctx context.Context, config *OAuthConfig) (OAuthToken, error) { + if config == nil || config.RefreshToken == "" { + return OAuthToken{}, fmt.Errorf("no refresh token available") + } + + // Check if token is still valid: not expired and not expiring within next minute. + if !config.AccessTokenExpiresAt.IsZero() && time.Now().Before(config.AccessTokenExpiresAt.Add(-1*time.Minute)) { + return config.OAuthToken, nil + } + + // Token is expired or about to expire, refresh it. + cfg := c.createOAuth2Config("") + tokenSource := cfg.TokenSource(ctx, &oauth2.Token{RefreshToken: config.RefreshToken}) + newToken, err := tokenSource.Token() + if err != nil { + if requiresLogin(err) { + return c.Login(ctx) + } + return OAuthToken{}, fmt.Errorf("failed to refresh token: %w", err) + } + + token := oauthTokenFromOAuth2(newToken) + token.AccessTokenRefreshed = true + return token, nil +} + +// requiresLogin checks if the error indicates an invalid or expired refresh token. +func requiresLogin(err error) bool { + var retrieveErr *oauth2.RetrieveError + if errors.As(err, &retrieveErr) && retrieveErr.ErrorCode == "invalid_grant" { + return true + } + return false +} diff --git a/cliext/oauth_test.go b/cliext/oauth_test.go new file mode 100644 index 000000000..5348576c4 --- /dev/null +++ b/cliext/oauth_test.go @@ -0,0 +1,325 @@ +package cliext_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/temporalio/cli/cliext" +) + +type mockOAuthServer struct { + t *testing.T + server *httptest.Server + authURL string + tokenURL string + + AuthorizeHandler func(http.ResponseWriter, *http.Request) + TokenExchangeHandler func(http.ResponseWriter, *http.Request) // authorization_code grant + TokenRefreshHandler func(http.ResponseWriter, *http.Request) // refresh_token grant + + capturedAuthURL atomic.Value +} + +func newMockOAuthServer(t *testing.T) *mockOAuthServer { + m := &mockOAuthServer{t: t} + + mux := http.NewServeMux() + mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { + if m.AuthorizeHandler == nil { + http.Error(w, "AuthorizeHandler not set", http.StatusInternalServerError) + return + } + m.AuthorizeHandler(w, r) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + w.Header().Set("Content-Type", "application/json") + switch r.FormValue("grant_type") { + case "authorization_code": + if m.TokenExchangeHandler == nil { + http.Error(w, "TokenExchangeHandler not set", http.StatusInternalServerError) + return + } + m.TokenExchangeHandler(w, r) + case "refresh_token": + if m.TokenRefreshHandler == nil { + http.Error(w, "TokenRefreshHandler not set", http.StatusInternalServerError) + return + } + m.TokenRefreshHandler(w, r) + } + }) + + m.server = httptest.NewServer(mux) + m.authURL = m.server.URL + "/authorize" + m.tokenURL = m.server.URL + "/token" + t.Cleanup(m.server.Close) + + return m +} + +func (m *mockOAuthServer) newClient(cfg cliext.OAuthClientConfig) *cliext.OAuthClient { + cfg.AuthURL = m.authURL + cfg.TokenURL = m.tokenURL + c := cliext.NewOAuthClient(cfg) + c.OnAuthURL = func(url string) { + go func() { + resp, _ := http.Get(url) + resp.Body.Close() + }() + } + return c +} + +func (m *mockOAuthServer) redirectWithCode(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + http.Redirect(w, r, fmt.Sprintf("%s?code=test-code&state=%s", + query.Get("redirect_uri"), query.Get("state")), http.StatusFound) +} + +func TestOAuthClient_Login(t *testing.T) { + s := newMockOAuthServer(t) + + s.AuthorizeHandler = s.redirectWithCode + s.TokenExchangeHandler = func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{ + "access_token": "test-access-token", + "refresh_token": "test-refresh-token", + "token_type": "Bearer", + "expires_in": 3600, + }) + } + + c := s.newClient(cliext.OAuthClientConfig{ClientID: "test-client"}) + + token, err := login(t, c) + + require.NoError(t, err) + assert.Equal(t, "test-access-token", token.AccessToken) + assert.Equal(t, "test-refresh-token", token.RefreshToken) + assert.Equal(t, "Bearer", token.TokenType) +} + +func TestOAuthClient_Login_RequestParams(t *testing.T) { + var audience, custom string + + s := newMockOAuthServer(t) + s.AuthorizeHandler = func(w http.ResponseWriter, r *http.Request) { + audience = r.URL.Query().Get("audience") + custom = r.URL.Query().Get("custom") + s.redirectWithCode(w, r) + } + s.TokenExchangeHandler = func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{"access_token": "token"}) + } + + c := s.newClient(cliext.OAuthClientConfig{ + ClientID: "test-client", + RequestParams: map[string]string{ + "audience": "https://api.example.com", + "custom": "value", + }, + }) + + _, err := login(t, c) + + require.NoError(t, err) + assert.Equal(t, "https://api.example.com", audience) + assert.Equal(t, "value", custom) +} + +func TestOAuthClient_Login_Scopes(t *testing.T) { + var scopes string + + s := newMockOAuthServer(t) + s.AuthorizeHandler = func(w http.ResponseWriter, r *http.Request) { + scopes = r.URL.Query().Get("scope") + s.redirectWithCode(w, r) + } + s.TokenExchangeHandler = func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"access_token":"ok"}`) + } + + c := s.newClient(cliext.OAuthClientConfig{ + ClientID: "test-client", + Scopes: []string{"openid", "profile", "email"}, + }) + + _, err := login(t, c) + + require.NoError(t, err) + assert.Contains(t, scopes, "openid") + assert.Contains(t, scopes, "profile") + assert.Contains(t, scopes, "email") +} + +func TestOAuthClient_Login_InvalidState(t *testing.T) { + s := newMockOAuthServer(t) + s.AuthorizeHandler = func(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + http.Redirect(w, r, fmt.Sprintf("%s?code=test-code&state=wrong-state", + query.Get("redirect_uri")), http.StatusFound) + } + + c := s.newClient(cliext.OAuthClientConfig{ClientID: "test-client"}) + + _, err := login(t, c) + + assert.ErrorContains(t, err, "invalid state") +} + +func TestOAuthClient_Login_ErrorCallback(t *testing.T) { + s := newMockOAuthServer(t) + s.AuthorizeHandler = func(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + http.Redirect(w, r, fmt.Sprintf("%s?error=access_denied&error_description=User+denied+access&state=%s", + query.Get("redirect_uri"), query.Get("state")), http.StatusFound) + } + + c := s.newClient(cliext.OAuthClientConfig{ClientID: "test-client"}) + + _, err := login(t, c) + assert.ErrorContains(t, err, "User denied access") +} + +func TestOAuthClient_Login_PKCE(t *testing.T) { + var codeChallenge, codeChallengeMethod, codeVerifier string + + s := newMockOAuthServer(t) + s.AuthorizeHandler = func(w http.ResponseWriter, r *http.Request) { + codeChallenge = r.URL.Query().Get("code_challenge") + codeChallengeMethod = r.URL.Query().Get("code_challenge_method") + s.redirectWithCode(w, r) + } + s.TokenExchangeHandler = func(w http.ResponseWriter, r *http.Request) { + codeVerifier = r.FormValue("code_verifier") + fmt.Fprint(w, `{"access_token":"ok"}`) + } + + c := s.newClient(cliext.OAuthClientConfig{ClientID: "test-client"}) + + _, err := login(t, c) + + require.NoError(t, err) + assert.NotEmpty(t, codeChallenge) + assert.Equal(t, "S256", codeChallengeMethod) + assert.NotEmpty(t, codeVerifier) +} + +func TestOAuthClient_Token_Refresh(t *testing.T) { + s := newMockOAuthServer(t) + s.TokenRefreshHandler = func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"access_token":"refreshed-token"}`) + } + + c := s.newClient(cliext.OAuthClientConfig{}) + + token, err := c.Token(t.Context(), &cliext.OAuthConfig{ + OAuthToken: cliext.OAuthToken{ + AccessTokenExpiresAt: time.Now(), + RefreshToken: "refresh-token", + }, + }) + + require.NoError(t, err) + assert.Equal(t, "refreshed-token", token.AccessToken) + assert.True(t, token.AccessTokenRefreshed) +} + +func TestOAuthClient_Token_ReLogin(t *testing.T) { + s := newMockOAuthServer(t) + s.AuthorizeHandler = s.redirectWithCode + s.TokenRefreshHandler = func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, `{"error":"invalid_grant"}`) + } + s.TokenExchangeHandler = func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"access_token":"relogin-token"}`) + } + + c := s.newClient(cliext.OAuthClientConfig{ClientID: "test-client"}) + + token, err := c.Token(t.Context(), &cliext.OAuthConfig{ + OAuthClientConfig: c.Options, + OAuthToken: cliext.OAuthToken{ + AccessTokenExpiresAt: time.Now().Add(-time.Hour), + RefreshToken: "invalid-refresh-token", + }, + }) + + require.NoError(t, err) + assert.Equal(t, "relogin-token", token.AccessToken) +} + +func TestOAuthClient_Token_ValidToken(t *testing.T) { + c := cliext.NewOAuthClient(cliext.OAuthClientConfig{}) + + token, err := c.Token(t.Context(), &cliext.OAuthConfig{ + OAuthToken: cliext.OAuthToken{ + AccessToken: "valid-token", + AccessTokenExpiresAt: time.Now().Add(time.Hour), + RefreshToken: "refresh-token", + }, + }) + + require.NoError(t, err) + assert.Equal(t, "valid-token", token.AccessToken) + assert.False(t, token.AccessTokenRefreshed) +} + +func TestOAuthClient_Token_NoRefreshToken(t *testing.T) { + c := cliext.NewOAuthClient(cliext.OAuthClientConfig{}) + + _, err := c.Token(t.Context(), nil) + assert.ErrorContains(t, err, "no refresh token") + + _, err = c.Token(t.Context(), &cliext.OAuthConfig{}) + assert.ErrorContains(t, err, "no refresh token") +} + +func TestOAuthClient_Token_RefreshError(t *testing.T) { + s := newMockOAuthServer(t) + s.TokenRefreshHandler = func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, `{"error":"server_error"}`) + } + + c := s.newClient(cliext.OAuthClientConfig{}) + + _, err := c.Token(t.Context(), &cliext.OAuthConfig{ + OAuthToken: cliext.OAuthToken{ + AccessTokenExpiresAt: time.Now().Add(-time.Hour), + RefreshToken: "refresh-token", + }, + }) + + assert.ErrorContains(t, err, "failed to refresh token") +} + +func login(t *testing.T, c *cliext.OAuthClient) (cliext.OAuthToken, error) { + t.Helper() + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + type result struct { + token cliext.OAuthToken + err error + } + ch := make(chan result, 1) + go func() { + token, err := c.Login(ctx) + ch <- result{token, err} + }() + + r := <-ch + return r.token, r.err +} diff --git a/cliext/profile.go b/cliext/profile.go new file mode 100644 index 000000000..2b15af308 --- /dev/null +++ b/cliext/profile.go @@ -0,0 +1,72 @@ +package cliext + +import ( + "go.temporal.io/sdk/contrib/envconfig" +) + +type Profile struct { + envconfig.ClientConfigProfile + OAuth *OAuthConfig +} + +type LoadProfileOptions struct { + envconfig.LoadClientConfigProfileOptions +} + +type LoadProfileResult struct { + // Config is the loaded configuration. + Config ClientConfig + // ConfigFilePath is the resolved path to the configuration file. + ConfigFilePath string + // ProfileName is the resolved profile name. + ProfileName string + // Profile points to Config.Profiles[ProfileName]. + Profile *Profile +} + +// LoadProfile loads a profile from the environment configuration. +func LoadProfile(opts LoadProfileOptions) (LoadProfileResult, error) { + envLookup := opts.EnvLookup + if envLookup == nil { + envLookup = envconfig.EnvLookupOS + } + + // Load the full configuration first to get all profiles. + configResult, err := LoadConfig(LoadConfigOptions{ + ConfigFilePath: opts.ConfigFilePath, + EnvLookup: envLookup, + }) + if err != nil { + return LoadProfileResult{}, err + } + + // Determine the profile name. + profileName := opts.ConfigFileProfile + if profileName == "" { + profileName, _ = envLookup.LookupEnv("TEMPORAL_PROFILE") + } + if profileName == "" { + profileName = envconfig.DefaultConfigFileProfile + } + + // Get or create the profile in the full config. + profile := configResult.Config.Profiles[profileName] + if profile == nil { + profile = &Profile{} + configResult.Config.Profiles[profileName] = profile + } + + // Apply environment variable overrides to the profile (unless disabled). + if !opts.DisableEnv { + if err := profile.ClientConfigProfile.ApplyEnvVars(envLookup); err != nil { + return LoadProfileResult{}, err + } + } + + return LoadProfileResult{ + Config: configResult.Config, + ConfigFilePath: configResult.ConfigFilePath, + ProfileName: profileName, + Profile: profile, + }, nil +} diff --git a/go.mod b/go.mod index cf4032f74..e03a52d9a 100644 --- a/go.mod +++ b/go.mod @@ -12,9 +12,10 @@ require ( github.com/mattn/go-isatty v0.0.20 github.com/nexus-rpc/sdk-go v0.3.0 github.com/olekukonko/tablewriter v0.0.5 - github.com/spf13/cobra v1.9.1 - github.com/spf13/pflag v1.0.6 + github.com/spf13/cobra v1.10.2 + github.com/spf13/pflag v1.0.9 github.com/stretchr/testify v1.10.0 + github.com/temporalio/cli/cliext v0.0.0 github.com/temporalio/ui-server/v2 v2.42.1 go.temporal.io/api v1.53.0 go.temporal.io/sdk v1.37.0 @@ -27,6 +28,8 @@ require ( modernc.org/sqlite v1.34.1 ) +replace github.com/temporalio/cli/cliext => ./cliext + require ( cel.dev/expr v0.23.1 // indirect cloud.google.com/go v0.120.0 // indirect @@ -106,6 +109,7 @@ require ( github.com/olivere/elastic/v7 v7.0.32 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pborman/uuid v1.2.1 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pkg/errors v0.9.1 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect @@ -156,7 +160,7 @@ require ( golang.org/x/crypto v0.38.0 // indirect golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect golang.org/x/net v0.40.0 // indirect - golang.org/x/oauth2 v0.30.0 // indirect + golang.org/x/oauth2 v0.33.0 // indirect golang.org/x/sync v0.14.0 // indirect golang.org/x/sys v0.33.0 // indirect golang.org/x/text v0.25.0 // indirect diff --git a/go.sum b/go.sum index 6926371e2..75d08d0c4 100644 --- a/go.sum +++ b/go.sum @@ -258,6 +258,8 @@ github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+ github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/pborman/uuid v1.2.1 h1:+ZZIw58t/ozdjRaXh/3awHfmWRbzYxJoAdNJxe/3pvw= github.com/pborman/uuid v1.2.1/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -303,10 +305,10 @@ github.com/sony/gobreaker v1.0.0 h1:feX5fGGXSl3dYd4aHZItw+FpHLvvoaqkawKjVNiFMNQ= github.com/sony/gobreaker v1.0.0/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w= github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= -github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= -github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= -github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= -github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spiffe/go-spiffe/v2 v2.5.0 h1:N2I01KCUkv1FAjZXJMwh95KK1ZIQLYbPfhaxw8WS0hE= github.com/spiffe/go-spiffe/v2 v2.5.0/go.mod h1:P+NxobPc6wXhVtINNtFjNWGBTreew1GBUCwT2wPmb7g= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -411,6 +413,7 @@ go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9E go.uber.org/zap v1.14.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -453,8 +456,8 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY= golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds= -golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= -golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= +golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo= +golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -477,6 +480,7 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/devserver/server.go b/internal/devserver/server.go index 230107cfc..7d8331945 100644 --- a/internal/devserver/server.go +++ b/internal/devserver/server.go @@ -35,6 +35,7 @@ import ( "strconv" "time" + "github.com/temporalio/cli/cliext" uiserver "github.com/temporalio/ui-server/v2/server" uiconfig "github.com/temporalio/ui-server/v2/server/config" uiserveroptions "github.com/temporalio/ui-server/v2/server/server_options" @@ -118,7 +119,7 @@ func Start(options StartOptions) (*Server, error) { } if options.FrontendHTTPPort == 0 { - options.FrontendHTTPPort = MustGetFreePort(options.FrontendIP) + options.FrontendHTTPPort = cliext.MustGetFreePort(options.FrontendIP) } // Build servers @@ -161,9 +162,9 @@ func (s *Server) Stop() { func (s *StartOptions) buildUIServer() *uiserver.Server { return uiserver.NewServer(uiserveroptions.WithConfigProvider(&uiconfig.Config{ - Host: MaybeEscapeIPv6(s.UIIP), + Host: cliext.MaybeEscapeIPv6(s.UIIP), Port: s.UIPort, - TemporalGRPCAddress: fmt.Sprintf("%v:%v", MaybeEscapeIPv6(s.FrontendIP), s.FrontendPort), + TemporalGRPCAddress: fmt.Sprintf("%v:%v", cliext.MaybeEscapeIPv6(s.FrontendIP), s.FrontendPort), EnableUI: true, PublicPath: s.PublicPath, UIAssetPath: s.UIAssetPath, @@ -233,13 +234,13 @@ func (s *StartOptions) buildServerOptions() ([]temporal.ServerOption, error) { dynConf[dynamicconfig.FrontendMaxNamespaceVisibilityRPSPerInstance.Key()] = 100 // NOTE that the URL scheme is fixed to HTTP since the dev server doesn't support TLS at the time of writing. dynConf[nexusoperations.CallbackURLTemplate.Key()] = fmt.Sprintf( - "http://%s:%d/namespaces/{{.NamespaceName}}/nexus/callback", MaybeEscapeIPv6(s.FrontendIP), s.FrontendHTTPPort) + "http://%s:%d/namespaces/{{.NamespaceName}}/nexus/callback", cliext.MaybeEscapeIPv6(s.FrontendIP), s.FrontendHTTPPort) dynConf[callbacks.AllowedAddresses.Key()] = []struct { Pattern string AllowInsecure bool }{ { - Pattern: fmt.Sprintf("%s:%d", MaybeEscapeIPv6(s.FrontendIP), s.FrontendHTTPPort), + Pattern: fmt.Sprintf("%s:%d", cliext.MaybeEscapeIPv6(s.FrontendIP), s.FrontendHTTPPort), AllowInsecure: true, }, } @@ -266,7 +267,7 @@ func (s *StartOptions) buildServerConfig() (*config.Config, error) { if conf.Global.Metrics == nil && s.MetricsPort > 0 { conf.Global.Metrics = &metrics.Config{ Prometheus: &metrics.PrometheusConfig{ - ListenAddress: fmt.Sprintf("%v:%v", MaybeEscapeIPv6(s.FrontendIP), s.MetricsPort), + ListenAddress: fmt.Sprintf("%v:%v", cliext.MaybeEscapeIPv6(s.FrontendIP), s.MetricsPort), HandlerPath: "/metrics", }, } @@ -294,8 +295,8 @@ func (s *StartOptions) buildServerConfig() (*config.Config, error) { s.CurrentClusterName: { Enabled: true, InitialFailoverVersion: int64(s.InitialFailoverVersion), - RPCAddress: fmt.Sprintf("%v:%v", MaybeEscapeIPv6(s.FrontendIP), s.FrontendPort), - HTTPAddress: fmt.Sprintf("%v:%v", MaybeEscapeIPv6(s.FrontendIP), s.FrontendHTTPPort), + RPCAddress: fmt.Sprintf("%v:%v", cliext.MaybeEscapeIPv6(s.FrontendIP), s.FrontendPort), + HTTPAddress: fmt.Sprintf("%v:%v", cliext.MaybeEscapeIPv6(s.FrontendIP), s.FrontendHTTPPort), ClusterID: s.ClusterID, }, }, @@ -312,7 +313,7 @@ func (s *StartOptions) buildServerConfig() (*config.Config, error) { conf.Archival.Visibility.State = "disabled" conf.NamespaceDefaults.Archival.History.State = "disabled" conf.NamespaceDefaults.Archival.Visibility.State = "disabled" - conf.PublicClient.HostPort = fmt.Sprintf("%v:%v", MaybeEscapeIPv6(s.FrontendIP), s.FrontendPort) + conf.PublicClient.HostPort = fmt.Sprintf("%v:%v", cliext.MaybeEscapeIPv6(s.FrontendIP), s.FrontendPort) return &conf, nil } @@ -364,7 +365,7 @@ func (s *StartOptions) buildServiceConfig(frontend bool) config.Service { conf.RPC.BindOnIP = s.FrontendIP conf.RPC.HTTPPort = s.FrontendHTTPPort } else { - conf.RPC.GRPCPort = MustGetFreePort(s.FrontendIP) + conf.RPC.GRPCPort = cliext.MustGetFreePort(s.FrontendIP) conf.RPC.BindOnIP = s.FrontendIP } return conf diff --git a/internal/temporalcli/client.go b/internal/temporalcli/client.go index 9299d4fc7..46b6303e9 100644 --- a/internal/temporalcli/client.go +++ b/internal/temporalcli/client.go @@ -8,6 +8,7 @@ import ( "os/user" "strings" + "github.com/temporalio/cli/cliext" "go.temporal.io/api/common/v1" "go.temporal.io/sdk/client" "go.temporal.io/sdk/contrib/envconfig" @@ -41,19 +42,21 @@ func (c *ClientOptions) dialClient(cctx *CommandContext) (client.Client, error) } // Load a client config profile - var clientProfile envconfig.ClientConfigProfile + var clientProfile *cliext.Profile if !cctx.RootCommand.DisableConfigFile || !cctx.RootCommand.DisableConfigEnv { - var err error - clientProfile, err = envconfig.LoadClientConfigProfile(envconfig.LoadClientConfigProfileOptions{ - ConfigFilePath: cctx.RootCommand.ConfigFile, - ConfigFileProfile: cctx.RootCommand.Profile, - DisableFile: cctx.RootCommand.DisableConfigFile, - DisableEnv: cctx.RootCommand.DisableConfigEnv, - EnvLookup: cctx.Options.EnvLookup, + profileResult, err := cliext.LoadProfile(cliext.LoadProfileOptions{ + LoadClientConfigProfileOptions: envconfig.LoadClientConfigProfileOptions{ + ConfigFilePath: cctx.RootCommand.ConfigFile, + ConfigFileProfile: cctx.RootCommand.Profile, + DisableFile: cctx.RootCommand.DisableConfigFile, + DisableEnv: cctx.RootCommand.DisableConfigEnv, + EnvLookup: cctx.Options.EnvLookup, + }, }) if err != nil { return nil, fmt.Errorf("failed loading client config: %w", err) } + clientProfile = profileResult.Profile } // To support legacy TLS environment variables, if they are present, we will @@ -168,6 +171,20 @@ func (c *ClientOptions) dialClient(cctx *CommandContext) (client.Client, error) clientProfile.TLS = &envconfig.ClientConfigTLS{Disabled: true} } + // If OAuth is configured and no API key or (enabled) TLS is set, + // use the OAuth client to obtain an access token. + if clientProfile.OAuth != nil && + clientProfile.APIKey == "" && + clientProfile.TLS == nil && !clientProfile.TLS.Disabled { + + oauthClient := cliext.NewOAuthClient(clientProfile.OAuth.OAuthClientConfig) + token, err := oauthClient.Token(cctx, clientProfile.OAuth) + if err != nil { + return nil, fmt.Errorf("failed to get OAuth token: %w", err) + } + clientProfile.APIKey = token.AccessToken + } + // If codec endpoint is set, create codec setting regardless. But if auth is // set, it only overrides if codec is present. if c.CodecEndpoint != "" { diff --git a/internal/temporalcli/commands.config.go b/internal/temporalcli/commands.config.go index 79467328d..b30d75a72 100644 --- a/internal/temporalcli/commands.config.go +++ b/internal/temporalcli/commands.config.go @@ -2,13 +2,12 @@ package temporalcli import ( "fmt" - "os" - "path/filepath" "reflect" "sort" "strings" "github.com/BurntSushi/toml" + "github.com/temporalio/cli/cliext" "github.com/temporalio/cli/internal/printer" "go.temporal.io/sdk/contrib/envconfig" ) @@ -23,9 +22,18 @@ func (c *TemporalConfigDeleteCommand) run(cctx *CommandContext, _ []string) erro if strings.HasPrefix(c.Prop, "grpc_meta.") { key := strings.TrimPrefix(c.Prop, "grpc_meta.") if _, ok := confProfile.GRPCMeta[key]; !ok { - return fmt.Errorf("gRPC meta key %q not found", key) + return fmt.Errorf("property %q not found", c.Prop) } delete(confProfile.GRPCMeta, key) + } else if strings.HasPrefix(c.Prop, "oauth.request_params.") { + key := strings.TrimPrefix(c.Prop, "oauth.request_params.") + if confProfile.OAuth == nil || confProfile.OAuth.RequestParams == nil { + return fmt.Errorf("property %q not found", c.Prop) + } + if _, ok := confProfile.OAuth.RequestParams[key]; !ok { + return fmt.Errorf("property %q not found", c.Prop) + } + delete(confProfile.OAuth.RequestParams, key) } else { reflectVal, err := reflectEnvConfigProp(confProfile, c.Prop, true) if err != nil { @@ -60,7 +68,7 @@ func (c *TemporalConfigDeleteProfileCommand) run(cctx *CommandContext, _ []strin func (c *TemporalConfigGetCommand) run(cctx *CommandContext, _ []string) error { // Load config profile profileName := envConfigProfileName(cctx) - conf, confProfile, err := loadEnvConfigProfile(cctx, profileName, true) + _, confProfile, err := loadEnvConfigProfile(cctx, profileName, true) if err != nil { return err } @@ -72,17 +80,26 @@ func (c *TemporalConfigGetCommand) run(cctx *CommandContext, _ []string) error { if c.Prop != "" { // We do not support asking for structures with children at this time, // but "tls" is a special case because it's also a bool. - if c.Prop == "codec" || c.Prop == "grpc_meta" { + if c.Prop == "codec" || c.Prop == "grpc_meta" || c.Prop == "oauth" || c.Prop == "oauth.request_params" { return fmt.Errorf("must provide exact property, not parent property") } var reflectVal reflect.Value - // gRPC meta is special + // gRPC meta and OAuth request params are special if strings.HasPrefix(c.Prop, "grpc_meta.") { v, ok := confProfile.GRPCMeta[strings.TrimPrefix(c.Prop, "grpc_meta.")] if !ok { return fmt.Errorf("unknown property %q", c.Prop) } reflectVal = reflect.ValueOf(v) + } else if strings.HasPrefix(c.Prop, "oauth.request_params.") { + if confProfile.OAuth == nil || confProfile.OAuth.RequestParams == nil { + return fmt.Errorf("unknown property %q", c.Prop) + } + v, ok := confProfile.OAuth.RequestParams[strings.TrimPrefix(c.Prop, "oauth.request_params.")] + if !ok { + return fmt.Errorf("unknown property %q", c.Prop) + } + reflectVal = reflect.ValueOf(v) } else { // Single value goes into property-value structure reflectVal, err = reflectEnvConfigProp(confProfile, c.Prop, false) @@ -104,7 +121,12 @@ func (c *TemporalConfigGetCommand) run(cctx *CommandContext, _ []string) error { var tomlConf struct { Profiles map[string]any `toml:"profile"` } - if b, err := conf.ToTOML(envconfig.ClientConfigToTOMLOptions{}); err != nil { + cliextConfig := &cliext.ClientConfig{ + Profiles: map[string]*cliext.Profile{ + profileName: confProfile, + }, + } + if b, err := cliext.ConfigToTOML(cliextConfig); err != nil { return fmt.Errorf("failed converting to TOML: %w", err) } else if err := toml.Unmarshal(b, &tomlConf); err != nil { return fmt.Errorf("failed converting from TOML: %w", err) @@ -129,11 +151,18 @@ func (c *TemporalConfigGetCommand) run(cctx *CommandContext, _ []string) error { } } - // Add "grpc_meta" + // Add grpc_meta for k, v := range confProfile.GRPCMeta { props = append(props, prop{Property: "grpc_meta." + k, Value: v}) } + // Add oauth.request_params + if confProfile.OAuth != nil { + for k, v := range confProfile.OAuth.RequestParams { + props = append(props, prop{Property: "oauth.request_params." + k, Value: v}) + } + } + // Sort and display sort.Slice(props, func(i, j int) bool { return props[i].Property < props[j].Property }) return cctx.Printer.PrintStructured(props, printer.StructuredOptions{Table: &printer.TableOptions{}}) @@ -141,7 +170,7 @@ func (c *TemporalConfigGetCommand) run(cctx *CommandContext, _ []string) error { } func (c *TemporalConfigListCommand) run(cctx *CommandContext, _ []string) error { - clientConfig, err := envconfig.LoadClientConfig(envconfig.LoadClientConfigOptions{ + loadResult, err := cliext.LoadConfig(cliext.LoadConfigOptions{ ConfigFilePath: cctx.RootCommand.ConfigFile, EnvLookup: cctx.Options.EnvLookup, }) @@ -151,8 +180,8 @@ func (c *TemporalConfigListCommand) run(cctx *CommandContext, _ []string) error type profile struct { Name string `json:"name"` } - profiles := make([]profile, 0, len(clientConfig.Profiles)) - for k := range clientConfig.Profiles { + profiles := make([]profile, 0, len(loadResult.Config.Profiles)) + for k := range loadResult.Config.Profiles { profiles = append(profiles, profile{Name: k}) } sort.Slice(profiles, func(i, j int) bool { return profiles[i].Name < profiles[j].Name }) @@ -165,12 +194,20 @@ func (c *TemporalConfigSetCommand) run(cctx *CommandContext, _ []string) error { if err != nil { return err } - // As a special case, "grpc_meta." values are handled specifically + // gRPC meta and OAuth request params are handled specifically if strings.HasPrefix(c.Prop, "grpc_meta.") { if confProfile.GRPCMeta == nil { confProfile.GRPCMeta = map[string]string{} } confProfile.GRPCMeta[strings.TrimPrefix(c.Prop, "grpc_meta.")] = c.Value + } else if strings.HasPrefix(c.Prop, "oauth.request_params.") { + if confProfile.OAuth == nil { + confProfile.OAuth = &cliext.OAuthConfig{} + } + if confProfile.OAuth.RequestParams == nil { + confProfile.OAuth.RequestParams = map[string]string{} + } + confProfile.OAuth.RequestParams[strings.TrimPrefix(c.Prop, "oauth.request_params.")] = c.Value } else { // Get reflect value reflectVal, err := reflectEnvConfigProp(confProfile, c.Prop, false) @@ -195,10 +232,24 @@ func (c *TemporalConfigSetCommand) run(cctx *CommandContext, _ []string) error { return fmt.Errorf("must be 'true' or 'false' to set this property") } case reflect.Slice: - if reflectVal.Type().Elem().Kind() != reflect.Uint8 { + switch reflectVal.Type().Elem().Kind() { + case reflect.Uint8: + // []byte - set as bytes + reflectVal.SetBytes([]byte(c.Value)) + case reflect.String: + // []string - split by comma + if c.Value == "" { + reflectVal.Set(reflect.MakeSlice(reflectVal.Type(), 0, 0)) + } else { + parts := strings.Split(c.Value, ",") + for i := range parts { + parts[i] = strings.TrimSpace(parts[i]) + } + reflectVal.Set(reflect.ValueOf(parts)) + } + default: return fmt.Errorf("unexpected slice of type %v", reflectVal.Type()) } - reflectVal.SetBytes([]byte(c.Value)) case reflect.Bool: if c.Value != "true" && c.Value != "false" { return fmt.Errorf("must be 'true' or 'false' to set this property") @@ -228,25 +279,25 @@ func loadEnvConfigProfile( cctx *CommandContext, profile string, failIfNotFound bool, -) (*envconfig.ClientConfig, *envconfig.ClientConfigProfile, error) { - clientConfig, err := envconfig.LoadClientConfig(envconfig.LoadClientConfigOptions{ +) (cliext.ClientConfig, *cliext.Profile, error) { + loadResult, err := cliext.LoadConfig(cliext.LoadConfigOptions{ ConfigFilePath: cctx.RootCommand.ConfigFile, EnvLookup: cctx.Options.EnvLookup, }) if err != nil { - return nil, nil, err + return cliext.ClientConfig{}, nil, err } // Load profile - clientProfile := clientConfig.Profiles[profile] + clientProfile := loadResult.Config.Profiles[profile] if clientProfile == nil { if failIfNotFound { - return nil, nil, fmt.Errorf("profile %q not found", profile) + return cliext.ClientConfig{}, nil, fmt.Errorf("profile %q not found", profile) } - clientProfile = &envconfig.ClientConfigProfile{} - clientConfig.Profiles[profile] = clientProfile + clientProfile = &cliext.Profile{} + loadResult.Config.Profiles[profile] = clientProfile } - return &clientConfig, clientProfile, nil + return loadResult.Config, clientProfile, nil } var envConfigPropsToFieldNames = map[string]string{ @@ -265,10 +316,19 @@ var envConfigPropsToFieldNames = map[string]string{ "tls.disable_host_verification": "DisableHostVerification", "codec.endpoint": "Endpoint", "codec.auth": "Auth", + "oauth.client_id": "ClientID", + "oauth.client_secret": "ClientSecret", + "oauth.auth_url": "AuthURL", + "oauth.token_url": "TokenURL", + "oauth.scopes": "Scopes", + "oauth.access_token": "AccessToken", + "oauth.refresh_token": "RefreshToken", + "oauth.token_type": "TokenType", + "oauth.expires_at": "AccessTokenExpiresAt", } func reflectEnvConfigProp( - prof *envconfig.ClientConfigProfile, + prof *cliext.Profile, prop string, failIfParentNotFound bool, ) (reflect.Value, error) { @@ -279,7 +339,7 @@ func reflectEnvConfigProp( } // Load reflect val - parentVal := reflect.ValueOf(prof) + parentVal := reflect.ValueOf(&prof.ClientConfigProfile).Elem() if strings.HasPrefix(prop, "tls.") { if prof.TLS == nil { if failIfParentNotFound { @@ -287,7 +347,7 @@ func reflectEnvConfigProp( } prof.TLS = &envconfig.ClientConfigTLS{} } - parentVal = reflect.ValueOf(prof.TLS) + parentVal = reflect.ValueOf(prof.TLS).Elem() } else if strings.HasPrefix(prop, "codec.") { if prof.Codec == nil { if failIfParentNotFound { @@ -295,41 +355,25 @@ func reflectEnvConfigProp( } prof.Codec = &envconfig.ClientConfigCodec{} } - parentVal = reflect.ValueOf(prof.Codec) - } - - // Return reflected field - if parentVal.Kind() == reflect.Pointer { - parentVal = parentVal.Elem() + parentVal = reflect.ValueOf(prof.Codec).Elem() + } else if strings.HasPrefix(prop, "oauth.") { + if prof.OAuth == nil { + if failIfParentNotFound { + return reflect.Value{}, fmt.Errorf("no OAuth options found") + } + prof.OAuth = &cliext.OAuthConfig{} + } + parentVal = reflect.ValueOf(prof.OAuth).Elem() } return parentVal.FieldByName(field), nil } -func writeEnvConfigFile(cctx *CommandContext, conf *envconfig.ClientConfig) error { - // Get file +func writeEnvConfigFile(cctx *CommandContext, conf cliext.ClientConfig) error { configFile := cctx.RootCommand.ConfigFile - if configFile == "" { - configFile, _ = cctx.Options.EnvLookup.LookupEnv("TEMPORAL_CONFIG_FILE") - if configFile == "" { - var err error - if configFile, err = envconfig.DefaultConfigFilePath(); err != nil { - return err - } - } - } - - // Convert to TOML - b, err := conf.ToTOML(envconfig.ClientConfigToTOMLOptions{}) - if err != nil { - return fmt.Errorf("failed building TOML: %w", err) - } - - // Write to file, making dirs as needed cctx.Logger.Info("Writing config file", "file", configFile) - if err := os.MkdirAll(filepath.Dir(configFile), 0700); err != nil { - return fmt.Errorf("failed making config file parent dirs: %w", err) - } else if err := os.WriteFile(configFile, b, 0600); err != nil { - return fmt.Errorf("failed writing config file: %w", err) - } - return nil + return cliext.WriteConfig(cliext.WriteConfigOptions{ + Config: conf, + ConfigFilePath: configFile, + EnvLookup: cctx.Options.EnvLookup, + }) } diff --git a/internal/temporalcli/commands.config_test.go b/internal/temporalcli/commands.config_test.go index 5cc89ec86..86392e1a4 100644 --- a/internal/temporalcli/commands.config_test.go +++ b/internal/temporalcli/commands.config_test.go @@ -5,7 +5,9 @@ import ( "encoding/json" "fmt" "os" + "strings" "testing" + "time" "github.com/BurntSushi/toml" ) @@ -39,7 +41,21 @@ server_ca_cert_path = "my-server-ca-cert-path" server_ca_cert_data = "my-server-ca-cert-data" # Intentionally absent # server_name = "my-server-name" -disable_host_verification = true`)) +disable_host_verification = true + +[profile.foo.oauth] +client_id = "my-oauth-client-id" +client_secret = "my-oauth-client-secret" +token_url = "https://example.com/oauth/token" +auth_url = "https://example.com/oauth/authorize" +access_token = "my-oauth-access-token" +refresh_token = "my-oauth-refresh-token" +token_type = "Bearer" +expires_at = "2318-03-23T00:00:00Z" +scopes = ["openid", "profile", "email"] + +[profile.foo.oauth.request_params] +audience = "https://api.example.com"`)) f.Close() h.NoError(err) env["TEMPORAL_CONFIG_FILE"] = f.Name() @@ -87,14 +103,29 @@ disable_host_verification = true`)) "tls.server_ca_cert_data": []byte("my-server-ca-cert-data"), "tls.server_name": "", "tls.disable_host_verification": true, + "oauth.client_id": "my-oauth-client-id", + "oauth.client_secret": "my-oauth-client-secret", + "oauth.token_url": "https://example.com/oauth/token", + "oauth.auth_url": "https://example.com/oauth/authorize", + "oauth.access_token": "my-oauth-access-token", + "oauth.refresh_token": "my-oauth-refresh-token", + "oauth.token_type": "Bearer", + "oauth.expires_at": time.Date(2318, 3, 23, 0, 0, 0, 0, time.UTC), + "oauth.scopes": []string{"openid", "profile", "email"}, + "oauth.request_params.audience": "https://api.example.com", } expectedNonJSON := make(map[string]any, len(expectedJSON)) for prop, expectedVal := range expectedJSON { if b, ok := expectedVal.([]byte); ok { expectedVal = "bytes(" + base64.StdEncoding.EncodeToString(b) + ")" - } else { - expectedNonJSON[prop] = expectedVal + } else if prop == "oauth.expires_at" { + // times display in relative format in text output + expectedVal = "a long while from now" + } else if s, ok := expectedVal.([]string); ok { + // Slices display as "[item1, item2, item3]" in text output + expectedVal = "[" + strings.Join(s, ", ") + "]" } + expectedNonJSON[prop] = expectedVal } // JSON individual @@ -127,6 +158,20 @@ disable_host_verification = true`)) "some-header3": "some-value3" }, "namespace": "my-namespace", + "oauth": { + "access_token": "my-oauth-access-token", + "auth_url": "https://example.com/oauth/authorize", + "client_id": "my-oauth-client-id", + "client_secret": "my-oauth-client-secret", + "expires_at": "2318-03-23T00:00:00Z", + "refresh_token": "my-oauth-refresh-token", + "request_params": { + "audience": "https://api.example.com" + }, + "scopes": ["openid", "profile", "email"], + "token_type": "Bearer", + "token_url": "https://example.com/oauth/token" + }, "tls": { "client_cert_data": "my-client-cert-data", "client_cert_path": "my-client-cert-path", @@ -317,21 +362,31 @@ func TestConfig_Set(t *testing.T) { // Set a bunch of other things toSet := map[string]string{ - "address": "my-address", - "namespace": "my-namespace", - "api_key": "my-api-key", - "codec.endpoint": "my-endpoint", - "codec.auth": "my-auth", - "grpc_meta.sOme_header1": "some-value1", - "tls": "true", - "tls.disabled": "true", - "tls.client_cert_path": "my-client-cert-path", - "tls.client_cert_data": "my-client-cert-data", - "tls.client_key_path": "my-client-key-path", - "tls.client_key_data": "my-client-key-data", - "tls.server_ca_cert_path": "my-server-ca-cert-path", - "tls.server_ca_cert_data": "my-server-ca-cert-data", - "tls.disable_host_verification": "true", + "address": "my-address", + "namespace": "my-namespace", + "api_key": "my-api-key", + "codec.endpoint": "my-endpoint", + "codec.auth": "my-auth", + "grpc_meta.sOme_header1": "some-value1", + "tls": "true", + "tls.disabled": "true", + "tls.client_cert_path": "my-client-cert-path", + "tls.client_cert_data": "my-client-cert-data", + "tls.client_key_path": "my-client-key-path", + "tls.client_key_data": "my-client-key-data", + "tls.server_ca_cert_path": "my-server-ca-cert-path", + "tls.server_ca_cert_data": "my-server-ca-cert-data", + "tls.disable_host_verification": "true", + "oauth.client_id": "test-oauth-client", + "oauth.client_secret": "test-oauth-secret", + "oauth.auth_url": "https://example.com/auth", + "oauth.token_url": "https://example.com/token", + "oauth.access_token": "test-access-token", + "oauth.refresh_token": "test-refresh-token", + "oauth.token_type": "Bearer", + "oauth.scopes": "read,write,admin", + "oauth.request_params.audience": "https://test-api.example.com", + "oauth.request_params.resource_id": "test-resource", } for k, v := range toSet { res = h.Execute("config", "set", "--prop", k, "--value", v) @@ -367,6 +422,20 @@ func TestConfig_Set(t *testing.T) { "grpc_meta": map[string]any{ "some-header1": "some-value1", }, + "oauth": map[string]any{ + "client_id": "test-oauth-client", + "client_secret": "test-oauth-secret", + "auth_url": "https://example.com/auth", + "token_url": "https://example.com/token", + "access_token": "test-access-token", + "refresh_token": "test-refresh-token", + "token_type": "Bearer", + "scopes": []any{"read", "write", "admin"}, + "request_params": map[string]any{ + "audience": "https://test-api.example.com", + "resource_id": "test-resource", + }, + }, }, }, }, diff --git a/internal/temporalcli/commands.server.go b/internal/temporalcli/commands.server.go index 91af9d801..a5d9f4471 100644 --- a/internal/temporalcli/commands.server.go +++ b/internal/temporalcli/commands.server.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "go.temporal.io/api/enums/v1" + "github.com/temporalio/cli/cliext" "github.com/temporalio/cli/internal/devserver" ) @@ -57,12 +58,12 @@ func (t *TemporalServerStartDevCommand) run(cctx *CommandContext, args []string) } else if err := opts.LogLevel.UnmarshalText([]byte(logLevel)); err != nil { return fmt.Errorf("invalid log level %q: %w", logLevel, err) } - if err := devserver.CheckPortFree(opts.FrontendIP, opts.FrontendPort); err != nil { + if err := cliext.CheckPortFree(opts.FrontendIP, opts.FrontendPort); err != nil { return fmt.Errorf("can't set frontend port %d: %w", opts.FrontendPort, err) } if opts.FrontendHTTPPort > 0 { - if err := devserver.CheckPortFree(opts.FrontendIP, opts.FrontendHTTPPort); err != nil { + if err := cliext.CheckPortFree(opts.FrontendIP, opts.FrontendHTTPPort); err != nil { return fmt.Errorf("can't set frontend HTTP port %d: %w", opts.FrontendHTTPPort, err) } } @@ -77,11 +78,11 @@ func (t *TemporalServerStartDevCommand) run(cctx *CommandContext, args []string) if opts.UIPort > 65535 { opts.UIPort = 65535 } - if err := devserver.CheckPortFree(opts.UIIP, opts.UIPort); err != nil { + if err := cliext.CheckPortFree(opts.UIIP, opts.UIPort); err != nil { return fmt.Errorf("can't use default UI port %d (%d + 1000): %w", opts.UIPort, t.Port, err) } } else { - if err := devserver.CheckPortFree(opts.UIIP, opts.UIPort); err != nil { + if err := cliext.CheckPortFree(opts.UIIP, opts.UIPort); err != nil { return fmt.Errorf("can't set UI port %d: %w", opts.UIPort, err) } } @@ -140,9 +141,9 @@ func (t *TemporalServerStartDevCommand) run(cctx *CommandContext, args []string) } // Grab a free port for metrics ahead-of-time so we know what port is selected if opts.MetricsPort == 0 { - opts.MetricsPort = devserver.MustGetFreePort(opts.FrontendIP) + opts.MetricsPort = cliext.MustGetFreePort(opts.FrontendIP) } else { - if err := devserver.CheckPortFree(opts.FrontendIP, opts.MetricsPort); err != nil { + if err := cliext.CheckPortFree(opts.FrontendIP, opts.MetricsPort); err != nil { return fmt.Errorf("can't set metrics port %d: %w", opts.MetricsPort, err) } } @@ -173,7 +174,7 @@ func toFriendlyIp(host string) string { if host == "127.0.0.1" || host == "::1" { return "localhost" } - return devserver.MaybeEscapeIPv6(host) + return cliext.MaybeEscapeIPv6(host) } func persistentClusterID() string { diff --git a/internal/temporalcli/commands.server_test.go b/internal/temporalcli/commands.server_test.go index 8c25558d9..14b37eac3 100644 --- a/internal/temporalcli/commands.server_test.go +++ b/internal/temporalcli/commands.server_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/temporalio/cli/internal/devserver" + "github.com/temporalio/cli/cliext" "go.temporal.io/api/operatorservice/v1" "go.temporal.io/sdk/client" "go.temporal.io/sdk/temporal" @@ -24,8 +24,8 @@ import ( // * Server reuse existing database file func TestServer_StartDev_Simple(t *testing.T) { - port := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) - httpPort := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) + port := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) + httpPort := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) startDevServerAndRunSimpleTest( t, // TODO(cretz): Remove --headless when @@ -36,8 +36,8 @@ func TestServer_StartDev_Simple(t *testing.T) { } func TestServer_StartDev_IPv4Unspecified(t *testing.T) { - port := strconv.Itoa(devserver.MustGetFreePort("0.0.0.0")) - httpPort := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) + port := strconv.Itoa(cliext.MustGetFreePort("0.0.0.0")) + httpPort := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) startDevServerAndRunSimpleTest( t, []string{"server", "start-dev", "--ip", "0.0.0.0", "-p", port, "--http-port", httpPort, "--headless"}, @@ -46,8 +46,8 @@ func TestServer_StartDev_IPv4Unspecified(t *testing.T) { } func TestServer_StartDev_SQLitePragma(t *testing.T) { - port := strconv.Itoa(devserver.MustGetFreePort("0.0.0.0")) - httpPort := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) + port := strconv.Itoa(cliext.MustGetFreePort("0.0.0.0")) + httpPort := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) dbFilename := filepath.Join(os.TempDir(), "devserver-sqlite-pragma.sqlite") defer func() { _ = os.Remove(dbFilename) @@ -80,8 +80,8 @@ func TestServer_StartDev_IPv6Unspecified(t *testing.T) { return } - port := strconv.Itoa(devserver.MustGetFreePort("::")) - httpPort := strconv.Itoa(devserver.MustGetFreePort("::")) + port := strconv.Itoa(cliext.MustGetFreePort("::")) + httpPort := strconv.Itoa(cliext.MustGetFreePort("::")) startDevServerAndRunSimpleTest( t, []string{ @@ -89,9 +89,9 @@ func TestServer_StartDev_IPv6Unspecified(t *testing.T) { "--ip", "::", "--ui-ip", "::1", "-p", port, "--http-port", httpPort, - "--ui-port", strconv.Itoa(devserver.MustGetFreePort("::")), - "--http-port", strconv.Itoa(devserver.MustGetFreePort("::")), - "--metrics-port", strconv.Itoa(devserver.MustGetFreePort("::"))}, + "--ui-port", strconv.Itoa(cliext.MustGetFreePort("::")), + "--http-port", strconv.Itoa(cliext.MustGetFreePort("::")), + "--metrics-port", strconv.Itoa(cliext.MustGetFreePort("::"))}, "[::]:"+port, ) } @@ -144,8 +144,8 @@ func TestServer_StartDev_ConcurrentStarts(t *testing.T) { defer h.Close() // Start in background, then wait for client to be able to connect - port := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) - httpPort := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) + port := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) + httpPort := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) resCh := make(chan *CommandResult, 1) go func() { resCh <- h.Execute("server", "start-dev", "-p", port, "--http-port", httpPort, "--headless", "--log-level", "never") @@ -198,8 +198,8 @@ func TestServer_StartDev_WithSearchAttributes(t *testing.T) { defer h.Close() // Start in background, then wait for client to be able to connect - port := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) - httpPort := strconv.Itoa(devserver.MustGetFreePort("127.0.0.1")) + port := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) + httpPort := strconv.Itoa(cliext.MustGetFreePort("127.0.0.1")) resCh := make(chan *CommandResult, 1) go func() { resCh <- h.Execute( diff --git a/internal/temporalcli/commands_test.go b/internal/temporalcli/commands_test.go index e23eccacc..f0d289cf9 100644 --- a/internal/temporalcli/commands_test.go +++ b/internal/temporalcli/commands_test.go @@ -18,6 +18,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/temporalio/cli/cliext" "github.com/temporalio/cli/internal/devserver" "github.com/temporalio/cli/internal/temporalcli" "go.temporal.io/api/enums/v1" @@ -194,8 +195,8 @@ type EnvLookupMap map[string]string func (e EnvLookupMap) Environ() []string { ret := make([]string, 0, len(e)) - for k := range e { - ret = append(ret, k) + for k, v := range e { + ret = append(ret, k+"="+v) } return ret } @@ -335,10 +336,10 @@ func StartDevServer(t *testing.T, options DevServerOptions) *DevServer { d.Options.FrontendIP = "127.0.0.1" } if d.Options.FrontendPort == 0 { - d.Options.FrontendPort = devserver.MustGetFreePort(d.Options.FrontendIP) + d.Options.FrontendPort = cliext.MustGetFreePort(d.Options.FrontendIP) } if d.Options.FrontendHTTPPort == 0 { - d.Options.FrontendHTTPPort = devserver.MustGetFreePort(d.Options.FrontendIP) + d.Options.FrontendHTTPPort = cliext.MustGetFreePort(d.Options.FrontendIP) } if len(d.Options.Namespaces) == 0 { d.Options.Namespaces = []string{