Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/dev/gpctl/cmd/public-api.go
2498 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cmd
6
7
import (
8
"context"
9
"crypto/tls"
10
"fmt"
11
"os"
12
13
"github.com/gitpod-io/gitpod/common-go/log"
14
"github.com/spf13/cobra"
15
"google.golang.org/grpc"
16
"google.golang.org/grpc/credentials"
17
"google.golang.org/grpc/credentials/insecure"
18
"google.golang.org/grpc/metadata"
19
)
20
21
var publicApiCmd = &cobra.Command{
22
Use: "api",
23
Short: "Interact with Public API services",
24
}
25
26
var publicApiCmdOpts struct {
27
address string
28
insecure bool
29
token string
30
}
31
32
func init() {
33
rootCmd.AddCommand(publicApiCmd)
34
35
publicApiCmd.PersistentFlags().StringVar(&publicApiCmdOpts.address, "address", "api.main.preview.gitpod-dev.com:443", "Address of the API endpoint. Must be in the form <host>:<port>.")
36
publicApiCmd.PersistentFlags().BoolVar(&publicApiCmdOpts.insecure, "insecure", false, "Disable TLS when making requests against the API. For testing purposes only.")
37
publicApiCmd.PersistentFlags().StringVar(&publicApiCmdOpts.token, "token", os.Getenv("GPCTL_PUBLICAPI_TOKEN"), "Authentication token to interact with the API")
38
}
39
40
func newPublicAPIConn() (*grpc.ClientConn, error) {
41
if publicApiCmdOpts.address == "" {
42
return nil, fmt.Errorf("empty connection address")
43
}
44
45
if publicApiCmdOpts.token == "" {
46
return nil, fmt.Errorf("empty connection token. Use --token or GPCTL_PUBLICAPI_TOKEN to provide one.")
47
}
48
49
log.Debugf("Establishing gRPC connection against %s", publicApiCmdOpts.address)
50
51
opts := []grpc.DialOption{
52
// attach token to requests to auth
53
grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
54
withAuth := metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+publicApiCmdOpts.token)
55
return invoker(withAuth, method, req, reply, cc, opts...)
56
}),
57
}
58
59
if publicApiCmdOpts.insecure {
60
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
61
} else {
62
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))
63
}
64
65
conn, err := grpc.Dial(publicApiCmdOpts.address, opts...)
66
if err != nil {
67
return nil, fmt.Errorf("failed to dial %s: %w", publicApiCmdOpts.address, err)
68
}
69
70
return conn, nil
71
}
72
73