Skip to content

Commit

Permalink
add revoke cmd (#31)
Browse files Browse the repository at this point in the history
* WIP: add revoke cmd

* rebase current main and implement revoke

* call close immediately
  • Loading branch information
hirosassa authored Apr 6, 2022
1 parent fb162ca commit ac2c292
Show file tree
Hide file tree
Showing 3 changed files with 313 additions and 7 deletions.
77 changes: 72 additions & 5 deletions bqrole/dataset.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ func PermitDataset(role bq.AccessRole, project string, users, datasets []string,
if err != nil {
return errors.New("failed to create bigquery Client")
}
defer client.Close()

fmt.Printf("PERMIT following roles\n")
fmt.Printf("project_id: %s\n", project)
fmt.Printf("role: %s\n", role)
fmt.Printf("datasets: %s\n", datasets)
Expand All @@ -51,8 +53,6 @@ func PermitDataset(role bq.AccessRole, project string, users, datasets []string,
}
}

defer client.Close()

policy, err := FetchCurrentPolicy(project)
if err != nil {
return fmt.Errorf("failed to fetch current policy: %s", err)
Expand All @@ -74,11 +74,11 @@ func PermitDataset(role bq.AccessRole, project string, users, datasets []string,
// grant permissions for each datasets
for _, dataset := range datasets {
for _, user := range users {
err := updateDatasetMetadata(ctx, client, role, dataset, user, bq.UserEmailEntity)
err := grantDatasetPermission(ctx, client, role, dataset, user, bq.UserEmailEntity)
if err != nil {
// try as group account
log.Warn().Msg("failed to permit using bq.UserEmailEntity, try bq.GroupEmailEnity")
err = updateDatasetMetadata(ctx, client, role, dataset, user, bq.GroupEmailEntity)
err = grantDatasetPermission(ctx, client, role, dataset, user, bq.GroupEmailEntity)
if err != nil {
return err
}
Expand All @@ -90,6 +90,51 @@ func PermitDataset(role bq.AccessRole, project string, users, datasets []string,
return nil
}

func RevokeDataset(role bq.AccessRole, project string, users, datasets []string, yes bool) error {
ctx := context.Background()
client, err := bq.NewClient(ctx, project)
if err != nil {
return errors.New("failed to create bigquery Client")
}
defer client.Close()

fmt.Printf("REVOKE following roles\n")
fmt.Printf("project_id: %s\n", project)
fmt.Printf("role: %s\n", role)
fmt.Printf("datasets: %s\n", datasets)
fmt.Printf("users: %s\n", users)

if !yes {
fmt.Printf("Are you sure? [y/n]")

reader := bufio.NewReader(os.Stdin)
res, err := reader.ReadString('\n')

if err != nil || strings.TrimSpace(res) != "y" {
fmt.Println("Abort.")
return nil
}
}

// revoke permissions for each datasets
for _, dataset := range datasets {
for _, user := range users {
err := revokeDatasetPermission(ctx, client, role, dataset, user, bq.UserEmailEntity)
if err != nil {
// try as group account
log.Warn().Msg("failed to revoke using bq.UserEmailEntity, try bq.GroupEmailEnity")
err = revokeDatasetPermission(ctx, client, role, dataset, user, bq.GroupEmailEntity)
if err != nil {
return err
}
}
fmt.Printf("Revoke %s to %s access as %s\n", user, dataset, role)
}
}

return nil
}

// grantBQRole grants user roles/bigquery permission
func grantBQRole(project, user, role string, policy *ProjectPolicy) error {
if hasBQRole(policy, user, role) {
Expand Down Expand Up @@ -120,7 +165,7 @@ func grantBQRole(project, user, role string, policy *ProjectPolicy) error {
return nil
}

func updateDatasetMetadata(ctx context.Context, client *bq.Client, role bq.AccessRole, dataset string, user string, entityType bq.EntityType) error {
func grantDatasetPermission(ctx context.Context, client *bq.Client, role bq.AccessRole, dataset string, user string, entityType bq.EntityType) error {
ds := client.Dataset(dataset)
meta, err := ds.Metadata(ctx)
if err != nil {
Expand All @@ -141,6 +186,28 @@ func updateDatasetMetadata(ctx context.Context, client *bq.Client, role bq.Acces
return nil
}

func revokeDatasetPermission(ctx context.Context, client *bq.Client, role bq.AccessRole, dataset string, user string, entityType bq.EntityType) error {
ds := client.Dataset(dataset)
meta, err := ds.Metadata(ctx)
if err != nil {
return err
}

var accesses []*bq.AccessEntry
for _, access := range meta.Access {
if access.EntityType == entityType && access.Entity == user && access.Role == role {
continue // skipping the target entity
}
accesses = append(accesses, access)
}

update := bq.DatasetMetadataToUpdate{Access: accesses}
if _, err := ds.Update(ctx, update, meta.ETag); err != nil {
return err
}
return nil
}

func hasBQRole(p *ProjectPolicy, user string, role string) bool {
for _, b := range p.Bindings {
if b.Role == role {
Expand Down
67 changes: 65 additions & 2 deletions bqrole/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ func PermitProject(role, project string, users []string, yes bool) error {
if err != nil {
return errors.New("failed to create bigquery Client")
}
defer client.Close()

fmt.Printf("PERMIT following PROJECT-WIDE permission\n")
fmt.Printf("project_id: %s\n", project)
fmt.Printf("role: %s\n", role)
fmt.Printf("users: %s\n", users)
Expand All @@ -47,8 +49,6 @@ func PermitProject(role, project string, users []string, yes bool) error {
}
}

defer client.Close()

policy, err := FetchCurrentPolicy(project)
if err != nil {
return fmt.Errorf("failed to fetch current policy: %s", err)
Expand All @@ -66,6 +66,48 @@ func PermitProject(role, project string, users []string, yes bool) error {
return nil
}

func RevokeProject(role, project string, users []string, yes bool) error {
ctx := context.Background()
client, err := bq.NewClient(ctx, project)
if err != nil {
return errors.New("failed to create bigquery Client")
}
defer client.Close()

fmt.Printf("REVOKE following PROJECT-WIDE permission\n")
fmt.Printf("project_id: %s\n", project)
fmt.Printf("role: %s\n", role)
fmt.Printf("users: %s\n", users)

if !yes {
fmt.Printf("If you proceeds, PROJECT-WIDE permission will be added. Are you sure? [y/n]")

reader := bufio.NewReader(os.Stdin)
res, err := reader.ReadString('\n')

if err != nil || strings.TrimSpace(res) != "y" {
fmt.Println("Abort.")
return nil
}
}

policy, err := FetchCurrentPolicy(project)
if err != nil {
return fmt.Errorf("failed to fetch current policy: %s", err)
}

// revoke project-wide role if needed
for _, user := range users {
err = revokeProjectRole(project, user, role, policy)
if err != nil {
return err
}
fmt.Printf("Revoke %s to %s access as %s\n", user, project, role)
}

return nil
}

func grantProjectRole(project, user, role string, policy *ProjectPolicy) error {
if hasProjectRole(policy, user, role) { // already has roles/viewer
log.Info().Msgf("%s already has a role: %s, project: %s. skipped.", user, role, project)
Expand All @@ -87,6 +129,27 @@ func grantProjectRole(project, user, role string, policy *ProjectPolicy) error {
return nil
}

func revokeProjectRole(project, user, role string, policy *ProjectPolicy) error {
if !hasProjectRole(policy, user, role) {
log.Info().Msgf("%s doesn't have a role: %s, project: %s. skipped.", user, role, project)
return nil
}

var member string
if isServiceAccount(user) {
member = "serviceAccount:" + user
} else {
member = "user:" + user
}

cmd := fmt.Sprintf("gcloud projects remove-iam-policy-binding %s --member %s --role %s", project, member, role)
if err := exec.Command("bash", "-c", cmd).Run(); err != nil {
return fmt.Errorf("failed to update policy bindings to revoke %s %s: %s\n%s", user, role, err, err.(*exec.ExitError).Stderr)
}

return nil
}

func hasProjectRole(p *ProjectPolicy, user, role string) bool {
for _, b := range p.Bindings {
if b.Role == role {
Expand Down
176 changes: 176 additions & 0 deletions cmd/revoke.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/*
Copyright © 2020 Hirohito Sasakawa
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
"errors"
"fmt"

"github.com/spf13/cobra"

"github.com/hirosassa/bqiam/bqrole"
)

func init() {
rootCmd.AddCommand(newRevokeCommand())
}

func newRevokeCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "revoke",
Short: "revokes some users to some access",
Long: `revokes some users to some datasets or project-wide access as READER or WRITER or OWNER
For example:
bqiam revoke dataset READER -p bq-project-id -u user1@email.com -u user2@email.com -d dataset1 -d dataset2
bqiam revoke project READER -p bq-project-id -u user1@email.com
`,
Run: func(cmd *cobra.Command, args []string) {
_ = cmd.Help()
},
}

cmd.PersistentFlags().BoolP("yes", "y", false, "Automatic yes to prompts")
cmd.AddCommand(
newRevokeDatasetCmd(),
newRevokeProjectCmd(),
)

return cmd
}

func newRevokeProjectCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "project [READER | WRITER] -p [bq-project-id (required)] -u [user(s) (required)]",
Short: "revokes some users to some project-wide access",
Long: `revoke project revokes some users to some project-wide access as READER or WRITER or OWNER
For example:
bqiam project READER -p bq-project-id -u user1@email.com -u user2@email.com`,
RunE: runRevokeProjectCmd,
}

cmd.Flags().StringP("project", "p", "", "Specify GCP project id")
err := cmd.MarkFlagRequired("project")
if err != nil {
panic(err)
}

cmd.Flags().StringSliceP("users", "u", []string{}, "Specify user email(s)")

_ = registerProjectsCompletions(cmd)
_ = registerUsersCompletions(cmd)

return cmd
}

func runRevokeProjectCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("READER or WRITER must be specified")
}

role, err := bqrole.ProjectRole(args[0])
if err != nil {
return fmt.Errorf("READER or WRITER must be specified: %s", err)
}

project, err := cmd.Flags().GetString("project")
if err != nil {
return fmt.Errorf("failed to parse project flag: %s", err)
}

users, err := cmd.Flags().GetStringSlice("users")
if err != nil {
return fmt.Errorf("failed to parse users flag: %s", err)
}

yes, err := cmd.Flags().GetBool("yes")
if err != nil {
return fmt.Errorf("failed to parse yes flag: %s", err)
}

err = bqrole.RevokeProject(role, project, users, yes)
if err != nil {
return fmt.Errorf("failed to revoke: %s", err)
}

return nil
}

func newRevokeDatasetCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "dataset [READER | WRITER | OWNER] -p [bq-project-id (required)] [flags]",
Short: "revokes some users to some datasets access",
Long: `revokes some users to some datasets access as READER or WRITER or OWNER
For example:
bqiam dataset READER -p bq-project-id -u user1@email.com -u user2@email.com -d dataset1 -d dataset2`,
RunE: runRevokeDatasetCmd,
}

cmd.Flags().StringP("project", "p", "", "Specify GCP project id")
err := cmd.MarkFlagRequired("project")
if err != nil {
panic(err)
}

cmd.Flags().StringSliceP("users", "u", []string{}, "Specify user email(s)")
cmd.Flags().StringSliceP("datasets", "d", []string{}, "Specify dataset(s)")

_ = registerProjectsCompletions(cmd)
_ = registerDatasetsCompletions(cmd)
_ = registerUsersCompletions(cmd)

return cmd
}

func runRevokeDatasetCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("READER or WRITER or OWNER must be specified")
}

role, err := bqrole.DatasetRole(args[0])
if err != nil {
return fmt.Errorf("READER or WRITER or OWNER must be specified: %s", err)
}

project, err := cmd.Flags().GetString("project")
if err != nil {
return fmt.Errorf("failed to parse project flag: %s", err)
}

users, err := cmd.Flags().GetStringSlice("users")
if err != nil {
return fmt.Errorf("failed to parse users flag: %s", err)
}

datasets, err := cmd.Flags().GetStringSlice("datasets")
if err != nil {
return fmt.Errorf("failed to parse datasets flag: %s", err)
}

yes, err := cmd.Flags().GetBool("yes")
if err != nil {
return fmt.Errorf("failed to parse yes flag: %s", err)
}

err = bqrole.RevokeDataset(role, project, users, datasets, yes)
if err != nil {
return fmt.Errorf("failed to revoke: %s", err)
}

return nil
}

0 comments on commit ac2c292

Please sign in to comment.