github.com/minio/mc@v0.0.0-20240503112107-b471de8d1882/cmd/admin-policy-create.go (about)

     1  // Copyright (c) 2015-2022 MinIO, Inc.
     2  //
     3  // This file is part of MinIO Object Storage stack
     4  //
     5  // This program is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Affero General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // This program is distributed in the hope that it will be useful
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU Affero General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Affero General Public License
    16  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package cmd
    19  
    20  import (
    21  	"fmt"
    22  	"os"
    23  
    24  	"github.com/fatih/color"
    25  	"github.com/minio/cli"
    26  	json "github.com/minio/colorjson"
    27  	"github.com/minio/madmin-go/v3"
    28  	"github.com/minio/mc/pkg/probe"
    29  	"github.com/minio/pkg/v2/console"
    30  )
    31  
    32  var adminPolicyCreateCmd = cli.Command{
    33  	Name:         "create",
    34  	Usage:        "create a new IAM policy",
    35  	Action:       mainAdminPolicyCreate,
    36  	OnUsageError: onUsageError,
    37  	Before:       setGlobalsFromContext,
    38  	Flags:        globalFlags,
    39  	CustomHelpTemplate: `NAME:
    40    {{.HelpName}} - {{.Usage}}
    41  
    42  USAGE:
    43    {{.HelpName}} TARGET POLICYNAME POLICYFILE
    44  
    45  POLICYNAME:
    46    Name of the canned policy on MinIO server.
    47  
    48  POLICYFILE:
    49    Name of the policy file associated with the policy name.
    50  
    51  FLAGS:
    52    {{range .VisibleFlags}}{{.}}
    53    {{end}}
    54  EXAMPLES:
    55    1. Create a new canned policy 'writeonly'.
    56       {{.Prompt}} {{.HelpName}} myminio writeonly /tmp/writeonly.json
    57   `,
    58  }
    59  
    60  // checkAdminPolicyCreateSyntax - validate all the passed arguments
    61  func checkAdminPolicyCreateSyntax(ctx *cli.Context) {
    62  	if len(ctx.Args()) != 3 {
    63  		showCommandHelpAndExit(ctx, 1) // last argument is exit code
    64  	}
    65  }
    66  
    67  // userPolicyMessage container for content message structure
    68  type userPolicyMessage struct {
    69  	op          string
    70  	Status      string            `json:"status"`
    71  	Policy      string            `json:"policy,omitempty"`
    72  	PolicyInfo  madmin.PolicyInfo `json:"policyInfo,omitempty"`
    73  	UserOrGroup string            `json:"userOrGroup,omitempty"`
    74  	IsGroup     bool              `json:"isGroup"`
    75  }
    76  
    77  func (u userPolicyMessage) accountType() string {
    78  	switch u.op {
    79  	case "attach", "detach":
    80  		if u.IsGroup {
    81  			return "group"
    82  		}
    83  		return "user"
    84  	}
    85  	return ""
    86  }
    87  
    88  func (u userPolicyMessage) String() string {
    89  	switch u.op {
    90  	case "info":
    91  		buf, e := json.MarshalIndent(u.PolicyInfo, "", " ")
    92  		fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
    93  		return string(buf)
    94  	case "list":
    95  		return console.Colorize("PolicyName", u.Policy)
    96  	case "remove":
    97  		return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
    98  	case "create":
    99  		return console.Colorize("PolicyMessage", "Created policy `"+u.Policy+"` successfully.")
   100  	case "detach":
   101  		return console.Colorize("PolicyMessage",
   102  			fmt.Sprintf("Policy `%s` successfully detached from %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
   103  	case "attach":
   104  		return console.Colorize("PolicyMessage",
   105  			fmt.Sprintf("Policy `%s` successfully attached to %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
   106  	}
   107  
   108  	return ""
   109  }
   110  
   111  func (u userPolicyMessage) JSON() string {
   112  	u.Status = "success"
   113  	jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
   114  	fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
   115  
   116  	return string(jsonMessageBytes)
   117  }
   118  
   119  // mainAdminPolicyCreate is the handle for "mc admin policy create" command.
   120  func mainAdminPolicyCreate(ctx *cli.Context) error {
   121  	checkAdminPolicyCreateSyntax(ctx)
   122  
   123  	console.SetColor("PolicyMessage", color.New(color.FgGreen))
   124  
   125  	// Get the alias parameter from cli
   126  	args := ctx.Args()
   127  	aliasedURL := args.Get(0)
   128  
   129  	policy, e := os.ReadFile(args.Get(2))
   130  	fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy")
   131  
   132  	// Create a new MinIO Admin Client
   133  	client, err := newAdminClient(aliasedURL)
   134  	fatalIf(err, "Unable to initialize admin connection.")
   135  
   136  	fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), policy)).Trace(args...), "Unable to create new policy")
   137  
   138  	printMsg(userPolicyMessage{
   139  		op:     ctx.Command.Name,
   140  		Policy: args.Get(1),
   141  	})
   142  
   143  	return nil
   144  }