Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions cmd/permctl/permctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,20 @@ package main
import (
"fmt"
"os"
"path/filepath"

"github.com/Permify/permify-cli/core/cli"
)

func main() {
home := os.Getenv("HOME")
defaultConfig := fmt.Sprintf("%s/.permctl", home)
home, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defaultConfig := filepath.Join(home, ".permctl")
shortDescription := "permctl is a cli for managing and communicating with permify"
permctl := cli.New("permctl", shortDescription, defaultConfig)
permctl := cli.New("permctl", shortDescription, defaultConfig)
cli.AddComponents(permctl.Cmd)
permctl.Execute()
}
43 changes: 36 additions & 7 deletions core/cli/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,42 @@ func validateFlags(cmd *cobra.Command, args []string) error {

func runE(cmd *cobra.Command, _ []string) error {
configFile, _ := cmd.Flags().GetString("config")
profile, _ := cmd.Flags().GetString("profile")

url, err := tui.StringPrompt("enter permify url", "", config.CliConfig.PermifyURL)
if err != nil {
return err
}

resp, err := client.New(url)
token, err := tui.StringPrompt("enter bearer token (optional)", "", config.CliConfig.Token)
if err != nil {
return err
}

certPath, err := tui.StringPrompt("enter client certificate path (optional)", "", config.CliConfig.CertPath)
if err != nil {
return err
}

certKey, err := tui.StringPrompt("enter client certificate key path (optional)", "", config.CliConfig.CertKey)
if err != nil {
return err
}

resp, err := client.New(client.Params{
Endpoint: url,
Token: token,
CertPath: certPath,
CertKey: certKey,
})
if err != nil {
return err
}

// Todo: Implement pagination
tenants, err := resp.Tenancy.List(context.Background(), &v1.TenantListRequest{})
if err != nil {
logger.Log.Fatal(err)
return err
}

tenantNames := []string{}
Expand All @@ -117,16 +141,21 @@ func runE(cmd *cobra.Command, _ []string) error {
tenantNames = append(tenantNames, nameID)
tenantIds[nameID] = tenant.Id
}

tenant, err := tui.Choice("Select a tenant: ", tenantNames)
if err != nil {
logger.Log.Error(err)
return err
}
config.CliConfig.PermifyURL = url
config.CliConfig.Tenant = tenantIds[tenant]
err = config.Write()
if err != nil {
logger.Log.Error(err)
config.CliConfig.Token = token
config.CliConfig.CertPath = certPath
config.CliConfig.CertKey = certKey
if err = config.WriteStoredCredentials(profile, config.CliConfig); err != nil {
return err
}
if err = config.Write(); err != nil {
return err
}
logger.Log.Info("successfully configured ", "config file", configFile)
return nil
Expand Down
125 changes: 121 additions & 4 deletions core/client/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,136 @@
package client

import (
"crypto/tls"
"fmt"
"net"
"strings"

"github.com/Permify/permify-cli/core/config"
permify "github.com/Permify/permify-go/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
)

// Params contains the connection material needed to initialize a Permify client.
type Params struct {
Endpoint string
Token string
CertPath string
CertKey string
}

type parsedEndpoint struct {
Target string
UseTLS bool
}

func parseEndpoint(endpoint string) parsedEndpoint {
trimmed := strings.TrimSpace(endpoint)
lower := strings.ToLower(trimmed)

switch {
case strings.HasPrefix(lower, "https://"):
return parsedEndpoint{Target: strings.TrimSpace(trimmed[len("https://"):]), UseTLS: true}
case strings.HasPrefix(lower, "grpcs://"):
return parsedEndpoint{Target: strings.TrimSpace(trimmed[len("grpcs://"):]), UseTLS: true}
case strings.HasPrefix(lower, "http://"):
return parsedEndpoint{Target: strings.TrimSpace(trimmed[len("http://"):])}
case strings.HasPrefix(lower, "grpc://"):
return parsedEndpoint{Target: strings.TrimSpace(trimmed[len("grpc://"):])}
default:
return parsedEndpoint{Target: trimmed}
}
}

func trimBearerPrefix(token string) string {
trimmed := strings.TrimSpace(token)
if len(trimmed) >= len("bearer ") && strings.EqualFold(trimmed[:len("bearer ")], "bearer ") {
return strings.TrimSpace(trimmed[len("bearer "):])
}
return trimmed
}

func serverName(target string) string {
host, _, err := net.SplitHostPort(target)
if err != nil {
return strings.Trim(target, "[]")
}
return strings.Trim(host, "[]")
}

func dialOptions(params Params) ([]grpc.DialOption, error) {
parsed := parseEndpoint(params.Endpoint)
params.Token = strings.TrimSpace(params.Token)
params.CertPath = strings.TrimSpace(params.CertPath)
params.CertKey = strings.TrimSpace(params.CertKey)
useTLS := parsed.UseTLS

if (params.CertPath == "") != (params.CertKey == "") {
return nil, fmt.Errorf("both cert_path and cert_key must be set together")
}

var options []grpc.DialOption
if params.CertPath != "" && params.CertKey != "" {
cert, err := tls.LoadX509KeyPair(params.CertPath, params.CertKey)
if err != nil {
return nil, fmt.Errorf("load client certificate: %w", err)
}
options = append(options, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
ServerName: serverName(parsed.Target),
})))
useTLS = true
} else if useTLS {
options = append(options, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
MinVersion: tls.VersionTLS12,
ServerName: serverName(parsed.Target),
})))
} else {
options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))
}

if token := trimBearerPrefix(params.Token); token != "" {
authorization := map[string]string{"authorization": "Bearer " + token}
if useTLS {
options = append(options, grpc.WithPerRPCCredentials(secureTokenCredentials(authorization)))
} else {
options = append(options, grpc.WithPerRPCCredentials(nonSecureTokenCredentials(authorization)))
}
}

return options, nil
}

// New initializes a new permify client
func New(endpoint string) (*permify.Client, error) {
func New(params Params) (*permify.Client, error) {
parsed := parseEndpoint(params.Endpoint)
if parsed.Target == "" {
return nil, fmt.Errorf("endpoint is empty")
}

options, err := dialOptions(params)
if err != nil {
return nil, err
}

client, err := permify.NewClient(
permify.Config{
Endpoint: endpoint,
Endpoint: parsed.Target,
},
// Todo: Implement secure call with tls certificate
grpc.WithTransportCredentials(insecure.NewCredentials()),
options...,
)
return client, err
}

// NewFromCLIConfig initializes a Permify client from the active profile.
func NewFromCLIConfig() (*permify.Client, error) {
return New(Params{
Endpoint: config.CliConfig.PermifyURL,
Token: config.CliConfig.Token,
CertPath: config.CliConfig.CertPath,
CertKey: config.CliConfig.CertKey,
})
}
Loading