-
Notifications
You must be signed in to change notification settings - Fork 292
feat(cli): add check, schema, data, and tenant management commands #2835
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
HarshadaGawas05
wants to merge
2
commits into
Permify:master
Choose a base branch
from
HarshadaGawas05:feat/cli-management-commands
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,3 +29,4 @@ node_modules | |
|
|
||
| pkg/development/wasm/main.wasm | ||
| pkg/development/wasm/play.wasm | ||
| /permify | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "strings" | ||
|
|
||
| "github.com/spf13/cobra" | ||
| "google.golang.org/grpc" | ||
|
|
||
| basev1 "github.com/Permify/permify/pkg/pb/base/v1" | ||
| ) | ||
|
|
||
| // NewCheckCommand runs a permission Check against a remote Permify gRPC server. | ||
| func NewCheckCommand() *cobra.Command { | ||
| var ( | ||
| credentialsPath string | ||
| tenantID string | ||
| subjectStr string | ||
| resourceStr string | ||
| permission string | ||
| ) | ||
|
|
||
| cmd := &cobra.Command{ | ||
| Use: "check", | ||
| Short: "Check whether a subject has a permission on a resource", | ||
| Long: `Calls the Permify Permission.Check RPC. | ||
|
|
||
| Subject is --entity (e.g. user:1). Resource is --resource (e.g. document:1).`, | ||
| RunE: func(cmd *cobra.Command, _ []string) error { | ||
| if strings.TrimSpace(tenantID) == "" { | ||
| return fmt.Errorf("--tenant-id is required") | ||
| } | ||
| if strings.TrimSpace(subjectStr) == "" { | ||
| return fmt.Errorf("--entity is required") | ||
| } | ||
| if strings.TrimSpace(resourceStr) == "" { | ||
| return fmt.Errorf("--resource is required") | ||
| } | ||
| if strings.TrimSpace(permission) == "" { | ||
| return fmt.Errorf("--permission is required") | ||
| } | ||
|
|
||
| subject, err := ParseSubjectRef(subjectStr) | ||
| if err != nil { | ||
| return fmt.Errorf("parse subject: %w", err) | ||
| } | ||
| entity, err := ParseEntityRef(resourceStr) | ||
| if err != nil { | ||
| return fmt.Errorf("parse resource: %w", err) | ||
| } | ||
|
|
||
| conn, err := DialGRPC(credentialsPath) | ||
| if err != nil { | ||
| return fmt.Errorf("connect to permify: %w", err) | ||
| } | ||
| defer func() { _ = conn.Close() }() | ||
|
|
||
| rpcCtx, cancel := newGRPCCallContext(cmd.Context()) | ||
| defer cancel() | ||
|
|
||
| client := basev1.NewPermissionClient(conn) | ||
| return runPermissionCheck(rpcCtx, os.Stdout, client, tenantID, entity, subject, permission) | ||
| }, | ||
| } | ||
|
|
||
| fs := cmd.Flags() | ||
| fs.StringVar(&credentialsPath, "credentials", "", "path to gRPC credentials file (default: $HOME/.permify/credentials)") | ||
| fs.StringVar(&tenantID, "tenant-id", "", "tenant identifier (required)") | ||
| fs.StringVar(&subjectStr, "entity", "", "subject as type:id (e.g. user:1)") | ||
| fs.StringVar(&resourceStr, "resource", "", "resource entity as type:id (e.g. document:1)") | ||
| fs.StringVar(&permission, "permission", "", "permission name to evaluate (e.g. view)") | ||
| _ = cmd.MarkFlagRequired("tenant-id") | ||
| _ = cmd.MarkFlagRequired("entity") | ||
| _ = cmd.MarkFlagRequired("resource") | ||
| _ = cmd.MarkFlagRequired("permission") | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| type permissionCheckClient interface { | ||
| Check(ctx context.Context, in *basev1.PermissionCheckRequest, opts ...grpc.CallOption) (*basev1.PermissionCheckResponse, error) | ||
| } | ||
|
|
||
| func runPermissionCheck( | ||
| ctx context.Context, | ||
| w io.Writer, | ||
| client permissionCheckClient, | ||
| tenantID string, | ||
| entity *basev1.Entity, | ||
| subject *basev1.Subject, | ||
| permission string, | ||
| ) error { | ||
| req := &basev1.PermissionCheckRequest{ | ||
| TenantId: tenantID, | ||
| Metadata: &basev1.PermissionCheckRequestMetadata{}, | ||
| Entity: entity, | ||
| Subject: subject, | ||
| Permission: permission, | ||
| } | ||
|
|
||
| resp, err := client.Check(ctx, req) | ||
| if err != nil { | ||
| return GRPCStatusError(err) | ||
| } | ||
| formatCheckResult(w, resp) | ||
| return nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| "google.golang.org/grpc" | ||
| "google.golang.org/grpc/codes" | ||
| "google.golang.org/grpc/status" | ||
|
|
||
| basev1 "github.com/Permify/permify/pkg/pb/base/v1" | ||
| ) | ||
|
|
||
| func TestRunPermissionCheck_Allowed(t *testing.T) { | ||
| t.Parallel() | ||
| var buf bytes.Buffer | ||
| stub := &stubPermissionClient{ | ||
| checkFn: func(_ context.Context, in *basev1.PermissionCheckRequest, _ ...grpc.CallOption) (*basev1.PermissionCheckResponse, error) { | ||
| assert.Equal(t, "t1", in.GetTenantId()) | ||
| assert.Equal(t, "view", in.GetPermission()) | ||
| return &basev1.PermissionCheckResponse{Can: basev1.CheckResult_CHECK_RESULT_ALLOWED}, nil | ||
| }, | ||
| } | ||
| ent := &basev1.Entity{Type: "document", Id: "1"} | ||
| sub := &basev1.Subject{Type: "user", Id: "1"} | ||
| rpcCtx, cancel := newGRPCCallContext(context.Background()) | ||
| defer cancel() | ||
| err := runPermissionCheck(rpcCtx, &buf, stub, "t1", ent, sub, "view") | ||
| require.NoError(t, err) | ||
| assert.Contains(t, buf.String(), "allowed") | ||
| } | ||
|
|
||
| func TestRunPermissionCheck_Denied(t *testing.T) { | ||
| t.Parallel() | ||
| var buf bytes.Buffer | ||
| stub := &stubPermissionClient{ | ||
| checkFn: func(_ context.Context, _ *basev1.PermissionCheckRequest, _ ...grpc.CallOption) (*basev1.PermissionCheckResponse, error) { | ||
| return &basev1.PermissionCheckResponse{Can: basev1.CheckResult_CHECK_RESULT_DENIED}, nil | ||
| }, | ||
| } | ||
| rpcCtx, cancel := newGRPCCallContext(context.Background()) | ||
| defer cancel() | ||
| err := runPermissionCheck(rpcCtx, &buf, stub, "t1", | ||
| &basev1.Entity{Type: "document", Id: "1"}, | ||
| &basev1.Subject{Type: "user", Id: "1"}, "edit") | ||
| require.NoError(t, err) | ||
| assert.Contains(t, buf.String(), "denied") | ||
| } | ||
|
|
||
| func TestRunPermissionCheck_RPCError(t *testing.T) { | ||
| t.Parallel() | ||
| var buf bytes.Buffer | ||
| stub := &stubPermissionClient{ | ||
| checkFn: func(_ context.Context, _ *basev1.PermissionCheckRequest, _ ...grpc.CallOption) (*basev1.PermissionCheckResponse, error) { | ||
| return nil, status.Errorf(codes.FailedPrecondition, "schema missing") | ||
| }, | ||
| } | ||
| rpcCtx, cancel := newGRPCCallContext(context.Background()) | ||
| defer cancel() | ||
| err := runPermissionCheck(rpcCtx, &buf, stub, "t1", | ||
| &basev1.Entity{Type: "document", Id: "1"}, | ||
| &basev1.Subject{Type: "user", Id: "1"}, "view") | ||
| require.Error(t, err) | ||
| assert.Contains(t, err.Error(), "schema missing") | ||
| } | ||
|
|
||
| func TestNewCheckCommand_RequiredFlags(t *testing.T) { | ||
| t.Parallel() | ||
| cmd := NewCheckCommand() | ||
| cmd.SetArgs([]string{}) | ||
| cmd.SetOut(bytes.NewBuffer(nil)) | ||
| cmd.SetErr(bytes.NewBuffer(nil)) | ||
| err := cmd.Execute() | ||
| require.Error(t, err) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/tls" | ||
| "crypto/x509" | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
|
|
||
| "google.golang.org/grpc" | ||
| "google.golang.org/grpc/credentials" | ||
| "google.golang.org/grpc/credentials/insecure" | ||
| "gopkg.in/yaml.v3" | ||
| ) | ||
|
|
||
| // CredentialsFile is the YAML format stored at ~/.permify/credentials (endpoint, optional api_token, tls_ca_path). | ||
| type CredentialsFile struct { | ||
| Endpoint string `yaml:"endpoint"` | ||
| APIToken string `yaml:"api_token"` | ||
| TLSCAPath string `yaml:"tls_ca_path"` | ||
| } | ||
|
|
||
| // DefaultCredentialsPath returns $HOME/.permify/credentials. | ||
| func DefaultCredentialsPath() (string, error) { | ||
| home, err := os.UserHomeDir() | ||
| if err != nil { | ||
| return "", fmt.Errorf("resolve home directory: %w", err) | ||
| } | ||
| return filepath.Join(home, ".permify", "credentials"), nil | ||
| } | ||
|
|
||
| // ResolveCredentialsPath returns flagPath if set, otherwise DefaultCredentialsPath. | ||
| func ResolveCredentialsPath(flagPath string) (string, error) { | ||
| if strings.TrimSpace(flagPath) != "" { | ||
| abs, err := filepath.Abs(flagPath) | ||
| if err != nil { | ||
| return "", fmt.Errorf("resolve credentials path: %w", err) | ||
| } | ||
| return abs, nil | ||
| } | ||
| return DefaultCredentialsPath() | ||
| } | ||
|
|
||
| // LoadCredentials reads and parses a credentials YAML file. | ||
| func LoadCredentials(path string) (*CredentialsFile, error) { | ||
| data, err := os.ReadFile(path) | ||
| if err != nil { | ||
| if os.IsNotExist(err) { | ||
| return nil, fmt.Errorf("credentials file not found at %q; create it with endpoint (and optional api_token, tls_ca_path): %w", path, err) | ||
| } | ||
| return nil, fmt.Errorf("read credentials file: %w", err) | ||
| } | ||
|
|
||
| var c CredentialsFile | ||
| if err := yaml.Unmarshal(data, &c); err != nil { | ||
| return nil, fmt.Errorf("parse credentials YAML: %w", err) | ||
| } | ||
|
|
||
| c.Endpoint = strings.TrimSpace(c.Endpoint) | ||
| c.APIToken = strings.TrimSpace(c.APIToken) | ||
| c.TLSCAPath = strings.TrimSpace(c.TLSCAPath) | ||
| if c.TLSCAPath != "" && !filepath.IsAbs(c.TLSCAPath) { | ||
| c.TLSCAPath = filepath.Join(filepath.Dir(path), c.TLSCAPath) | ||
| } | ||
|
|
||
| if c.Endpoint == "" { | ||
| return nil, fmt.Errorf("credentials file %q: endpoint is required", path) | ||
| } | ||
|
|
||
| return &c, nil | ||
| } | ||
|
|
||
| type bearerTokenCreds struct { | ||
| token string | ||
| } | ||
|
|
||
| func (b bearerTokenCreds) GetRequestMetadata(_ context.Context, _ ...string) (map[string]string, error) { | ||
| return map[string]string{"authorization": "Bearer " + b.token}, nil | ||
| } | ||
|
|
||
| func (b bearerTokenCreds) RequireTransportSecurity() bool { | ||
| return true | ||
| } | ||
|
|
||
| // GRPCDialOptions builds dial options: TLS + bearer token when api_token is set, otherwise insecure. | ||
| func GRPCDialOptions(c *CredentialsFile) ([]grpc.DialOption, error) { | ||
| token := strings.TrimSpace(c.APIToken) | ||
| if token == "" { | ||
| return []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}, nil | ||
| } | ||
|
|
||
| var tlsCfg *tls.Config | ||
| if c.TLSCAPath != "" { | ||
| pemData, err := os.ReadFile(c.TLSCAPath) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("read tls_ca_path: %w", err) | ||
| } | ||
| pool := x509.NewCertPool() | ||
| if !pool.AppendCertsFromPEM(pemData) { | ||
| return nil, fmt.Errorf("tls_ca_path: no PEM certificates found") | ||
| } | ||
| tlsCfg = &tls.Config{ | ||
| RootCAs: pool, | ||
| MinVersion: tls.VersionTLS12, | ||
| } | ||
| } else { | ||
| tlsCfg = &tls.Config{ | ||
| MinVersion: tls.VersionTLS12, | ||
| } | ||
| } | ||
|
|
||
| tc := credentials.NewTLS(tlsCfg) | ||
| return []grpc.DialOption{ | ||
| grpc.WithTransportCredentials(tc), | ||
| grpc.WithPerRPCCredentials(bearerTokenCreds{token: token}), | ||
| }, nil | ||
| } | ||
|
|
||
| // DialGRPC opens a client connection using a credentials file path. | ||
| func DialGRPC(credPath string) (*grpc.ClientConn, error) { | ||
| path, err := ResolveCredentialsPath(credPath) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("resolve credentials path: %w", err) | ||
| } | ||
| creds, err := LoadCredentials(path) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("load credentials: %w", err) | ||
| } | ||
| opts, err := GRPCDialOptions(creds) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("gRPC dial options: %w", err) | ||
| } | ||
| conn, err := grpc.NewClient(creds.Endpoint, opts...) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("dial gRPC %q: %w", creds.Endpoint, err) | ||
| } | ||
| return conn, nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.