-
Notifications
You must be signed in to change notification settings - Fork 141
/
client.go
81 lines (74 loc) · 2.09 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package client
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"connectrpc.com/connect"
"github.com/spf13/pflag"
"github.com/akuity/kargo/internal/cli/config"
"github.com/akuity/kargo/internal/cli/option"
"github.com/akuity/kargo/pkg/api/service/v1alpha1/svcv1alpha1connect"
)
type Options struct {
InsecureTLS bool
}
// AddFlags adds the flags for the client options to the provided flag set.
func (o *Options) AddFlags(flags *pflag.FlagSet) {
option.InsecureTLS(flags, &o.InsecureTLS)
}
// GetClientFromConfig returns a new client for the Kargo API server located at
// the address specified in local configuration, using credentials also
// specified in the local configuration.
func GetClientFromConfig(
ctx context.Context,
cfg config.CLIConfig,
opts Options,
) (
svcv1alpha1connect.KargoServiceClient,
error,
) {
if cfg.APIAddress == "" || cfg.BearerToken == "" {
return nil, errors.New(
"seems like you are not logged in; please use `kargo login` to authenticate",
)
}
skipTLSVerify := opts.InsecureTLS || cfg.InsecureSkipTLSVerify
cfg, err := newTokenRefresher().refreshToken(ctx, cfg, skipTLSVerify)
if err != nil {
return nil, fmt.Errorf("error refreshing token: %w", err)
}
return GetClient(cfg.APIAddress, cfg.BearerToken, skipTLSVerify), nil
}
// GetClient returns a new client for the Kargo API server located at the
// specified address. If the provided credential is non-empty, the client will
// be decorated with an interceptor that adds the credential to outbound
// requests.
func GetClient(
serverAddress string,
credential string,
insecureTLS bool,
) svcv1alpha1connect.KargoServiceClient {
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: insecureTLS, // nolint: gosec
},
},
}
if credential == "" {
return svcv1alpha1connect.NewKargoServiceClient(httpClient, serverAddress)
}
return svcv1alpha1connect.NewKargoServiceClient(
httpClient,
serverAddress,
connect.WithClientOptions(
connect.WithInterceptors(
&authInterceptor{
credential: credential,
},
),
),
)
}