Skip to content

Commit

Permalink
WIP: add revoke cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
hirosassa committed Apr 5, 2022
1 parent fb162ca commit 63073a8
Show file tree
Hide file tree
Showing 3 changed files with 289 additions and 4 deletions.
74 changes: 70 additions & 4 deletions bqrole/dataset.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func PermitDataset(role bq.AccessRole, project string, users, datasets []string,
return errors.New("failed to create bigquery Client")
}

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 Down Expand Up @@ -74,11 +75,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 +91,49 @@ func PermitDataset(role bq.AccessRole, project string, users, datasets []string,
return nil
}

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

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)
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
}

defer client.Close()

// 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 +164,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,7 +185,29 @@ func updateDatasetMetadata(ctx context.Context, client *bq.Client, role bq.Acces
return nil
}

func hasBQRole(p *ProjectPolicy, user string, role string) bool {
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 {
for _, m := range b.Members {
Expand Down
62 changes: 62 additions & 0 deletions bqrole/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func PermitProject(role, project string, users []string, yes bool) error {
return errors.New("failed to create bigquery Client")
}

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 Down Expand Up @@ -66,6 +67,46 @@ func PermitProject(role, project string, users []string, yes bool) error {
return nil
}

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

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)
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
}

defer client.Close()

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 +128,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
157 changes: 157 additions & 0 deletions cmd/revoke.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
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.AddCommand(
newRevokeDatasetCmd(),
)

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)")

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)
}

err = bqrole.RevokeProject(role, project, users)
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)")

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)
}

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

return nil
}

0 comments on commit 63073a8

Please sign in to comment.