refactor: gRPC connection setup into auth package

This commit is contained in:
abhisek 2024-10-02 21:57:57 +05:30
parent fce0410ae3
commit 476cd4d29d
No known key found for this signature in database
GPG Key ID: CB92A4990C02A88F
6 changed files with 73 additions and 35 deletions

View File

@ -23,7 +23,7 @@ var (
func newAuthCommand() *cobra.Command { func newAuthCommand() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "auth", Use: "auth",
Short: "Configure and verify Insights API authentication", Short: "[Deprecated] Use cloud command",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return errors.New("a valid sub-command is required") return errors.New("a valid sub-command is required")
}, },

13
cmd/cloud/main.go Normal file
View File

@ -0,0 +1,13 @@
package cloud
import "github.com/spf13/cobra"
func NewCloudCommand() *cobra.Command {
return &cobra.Command{
Use: "cloud",
Short: "Manage and query cloud resources (control plane)",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
}

45
internal/auth/grpc.go Normal file
View File

@ -0,0 +1,45 @@
package auth
import (
"fmt"
"net/http"
"net/url"
"os"
"github.com/safedep/vet/pkg/common/logger"
"google.golang.org/grpc"
drygrpc "github.com/safedep/dry/adapters/grpc"
)
// Create a gRPC client connection for the control plane
// based on available configuration
func ControlPlaneClientConnection(name string) (*grpc.ClientConn, error) {
parsedUrl, err := url.Parse(DefaultControlTowerUrl())
if err != nil {
return nil, err
}
host, port := parsedUrl.Hostname(), parsedUrl.Port()
if port == "" {
port = "443"
}
logger.Debugf("ControlTower host: %s, port: %s", host, port)
// For local development, we use the mock user.
vetTenantId := os.Getenv("VET_CONTROL_TOWER_TENANT_ID")
vetTenantMockUser := os.Getenv("VET_CONTROL_TOWER_MOCK_USER")
headers := http.Header{}
headers.Set("x-tenant-id", vetTenantId)
headers.Set("x-mock-user", vetTenantMockUser)
client, err := drygrpc.GrpcClient(name, host, port,
ApiKey(), headers, []grpc.DialOption{})
if err != nil {
return nil, fmt.Errorf("failed to create gRPC client: %w", err)
}
return client, nil
}

View File

@ -7,6 +7,7 @@ import (
"strconv" "strconv"
"github.com/safedep/dry/utils" "github.com/safedep/dry/utils"
"github.com/safedep/vet/cmd/cloud"
"github.com/safedep/vet/internal/ui" "github.com/safedep/vet/internal/ui"
"github.com/safedep/vet/pkg/common/logger" "github.com/safedep/vet/pkg/common/logger"
"github.com/safedep/vet/pkg/exceptions" "github.com/safedep/vet/pkg/exceptions"
@ -64,6 +65,7 @@ func main() {
cmd.AddCommand(newCodeCommand()) cmd.AddCommand(newCodeCommand())
cmd.AddCommand(newVersionCommand()) cmd.AddCommand(newVersionCommand())
cmd.AddCommand(newConnectCommand()) cmd.AddCommand(newConnectCommand())
cmd.AddCommand(cloud.NewCloudCommand())
cobra.OnInitialize(func() { cobra.OnInitialize(func() {
printBanner() printBanner()

View File

@ -3,9 +3,6 @@ package reporter
import ( import (
"context" "context"
"fmt" "fmt"
"net/http"
"net/url"
"os"
"strings" "strings"
"sync" "sync"
@ -14,7 +11,6 @@ import (
policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/policy/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/policy/v1"
vulnerabilityv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/vulnerability/v1" vulnerabilityv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/vulnerability/v1"
controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1"
drygrpc "github.com/safedep/dry/adapters/grpc"
"github.com/safedep/dry/utils" "github.com/safedep/dry/utils"
"github.com/safedep/vet/gen/checks" "github.com/safedep/vet/gen/checks"
"github.com/safedep/vet/pkg/analyzer" "github.com/safedep/vet/pkg/analyzer"
@ -32,9 +28,8 @@ const (
) )
type SyncReporterConfig struct { type SyncReporterConfig struct {
// ControlTower API Base URL // gRPC connection for ControlTower
ControlTowerBaseUrl string ClientConnection *grpc.ClientConn
ControlTowerToken string
// Enable multi-project syncing // Enable multi-project syncing
// In this case, a new project is created per package manifest // In this case, a new project is created per package manifest
@ -142,29 +137,8 @@ type syncReporter struct {
} }
func NewSyncReporter(config SyncReporterConfig) (Reporter, error) { func NewSyncReporter(config SyncReporterConfig) (Reporter, error) {
parsedUrl, err := url.Parse(config.ControlTowerBaseUrl) if config.ClientConnection == nil {
if err != nil { return nil, fmt.Errorf("missing gRPC client connection")
return nil, fmt.Errorf("failed to parse ControlTower base URL: %w", err)
}
host, port := parsedUrl.Hostname(), parsedUrl.Port()
if port == "" {
port = "443"
}
logger.Debugf("ControlTower host: %s, port: %s", host, port)
vetTenantId := os.Getenv("VET_CONTROL_TOWER_TENANT_ID")
vetTenantMockUser := os.Getenv("VET_CONTROL_TOWER_MOCK_USER") // Used in dev
headers := http.Header{}
headers.Set("x-tenant-id", vetTenantId)
headers.Set("x-mock-user", vetTenantMockUser)
client, err := drygrpc.GrpcClient("vet-sync", host, port,
config.ControlTowerToken, headers, []grpc.DialOption{})
if err != nil {
return nil, fmt.Errorf("failed to create gRPC client: %w", err)
} }
// TODO: Auto-discover config using CI environment variables // TODO: Auto-discover config using CI environment variables
@ -181,7 +155,7 @@ func NewSyncReporter(config SyncReporterConfig) (Reporter, error) {
logger.Debugf("Report Sync: Creating tool session for project: %s, version: %s", logger.Debugf("Report Sync: Creating tool session for project: %s, version: %s",
config.ProjectName, config.ProjectVersion) config.ProjectName, config.ProjectVersion)
toolServiceClient := controltowerv1grpc.NewToolServiceClient(client) toolServiceClient := controltowerv1grpc.NewToolServiceClient(config.ClientConnection)
toolSessionRes, err := toolServiceClient.CreateToolSession(context.Background(), toolSessionRes, err := toolServiceClient.CreateToolSession(context.Background(),
&controltowerv1.CreateToolSessionRequest{ &controltowerv1.CreateToolSessionRequest{
ToolName: config.ToolName, ToolName: config.ToolName,
@ -207,7 +181,7 @@ func NewSyncReporter(config SyncReporterConfig) (Reporter, error) {
config: &config, config: &config,
done: done, done: done,
workQueue: make(chan *workItem, 1000), workQueue: make(chan *workItem, 1000),
client: client, client: config.ClientConnection,
sessions: &syncSessionPool, sessions: &syncSessionPool,
} }

View File

@ -396,14 +396,18 @@ func internalStartScan() error {
} }
if syncReport { if syncReport {
clientConn, err := auth.ControlPlaneClientConnection("vet-sync")
if err != nil {
return err
}
rp, err := reporter.NewSyncReporter(reporter.SyncReporterConfig{ rp, err := reporter.NewSyncReporter(reporter.SyncReporterConfig{
ToolName: "vet", ToolName: "vet",
ToolVersion: version, ToolVersion: version,
ProjectName: syncReportProject, ProjectName: syncReportProject,
ProjectVersion: syncReportStream, ProjectVersion: syncReportStream,
ControlTowerBaseUrl: auth.DefaultControlTowerUrl(),
ControlTowerToken: auth.ApiKey(),
EnableMultiProjectSync: syncEnableMultiProject, EnableMultiProjectSync: syncEnableMultiProject,
ClientConnection: clientConn,
}) })
if err != nil { if err != nil {
return err return err