Support setting of custom policies from a JSON file (#2649)

Fixes #2633
This commit is contained in:
Praveen raj Mani
2019-01-28 13:30:31 -08:00
committed by kannappanr
parent e940856fee
commit 30965763d6
8 changed files with 109 additions and 48 deletions
+6
View File
@@ -16,6 +16,8 @@
package cmd
import "path/filepath"
// isValidAccessPERM - is provided access perm string supported.
func (b accessPerms) isValidAccessPERM() bool {
switch b {
@@ -25,6 +27,10 @@ func (b accessPerms) isValidAccessPERM() bool {
return false
}
func (b accessPerms) isValidAccessFile() bool {
return filepath.Ext(string(b)) == ".json"
}
// accessPerms - access level.
type accessPerms string
+3 -2
View File
@@ -918,9 +918,10 @@ func (f *fsClient) GetAccess() (access string, err *probe.Error) {
}
// SetAccess - set access policy permissions.
func (f *fsClient) SetAccess(access string) *probe.Error {
func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
// For windows this feature is not implemented.
if runtime.GOOS == "windows" {
// JSON policy for fs is not yet implemented.
if runtime.GOOS == "windows" || isJSON {
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
}
st, err := f.fsStat(false)
+1 -1
View File
@@ -228,7 +228,7 @@ func (s *TestSuite) TestBucketACLFails(c *C) {
// On windows setting permissions is not supported.
if runtime.GOOS != "windows" {
err = fsClient.SetAccess("readonly")
err = fsClient.SetAccess("readonly", false)
c.Assert(err, IsNil)
_, err = fsClient.GetAccess()
+7 -1
View File
@@ -943,11 +943,17 @@ func (c *s3Client) GetAccess() (string, *probe.Error) {
}
// SetAccess set access policy permissions.
func (c *s3Client) SetAccess(bucketPolicy string) *probe.Error {
func (c *s3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if bucket == "" {
return probe.NewError(BucketNameEmpty{})
}
if isJSON {
if e := c.api.SetBucketPolicy(bucket, bucketPolicy); e != nil {
return probe.NewError(e)
}
return nil
}
policyStr, e := c.api.GetBucketPolicy(bucket)
if e != nil {
return probe.NewError(e)
+1 -1
View File
@@ -54,7 +54,7 @@ type Client interface {
// Access policy operations.
GetAccess() (access string, error *probe.Error)
GetAccessRules() (policyRules map[string]string, error *probe.Error)
SetAccess(access string) *probe.Error
SetAccess(access string, isJSON bool) *probe.Error
// I/O operations
Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide) *probe.Error
+1 -1
View File
@@ -665,7 +665,7 @@ func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error {
// Set rule only if it doesn't exist in the target bucket
// or force flag is activated
if originalRule == "none" || isOverwrite {
err = dstClt.SetAccess(r)
err = dstClt.SetAccess(r, false)
if err != nil {
return err
}
+77 -42
View File
@@ -17,8 +17,12 @@
package cmd
import (
"bytes"
"encoding/json"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
@@ -48,12 +52,16 @@ var policyCmd = cli.Command{
USAGE:
{{.HelpName}} [FLAGS] PERMISSION TARGET
{{.HelpName}} [FLAGS] FILE TARGET
{{.HelpName}} [FLAGS] TARGET
{{.HelpName}} list [FLAGS] TARGET
PERMISSION:
Allowed policies are: [none, download, upload, public].
{{if .VisibleFlags}}
FILE:
A valid S3 policy JSON filepath.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
@@ -70,13 +78,16 @@ EXAMPLES:
4. Set a prefix to "public" on Amazon S3 cloud storage.
$ {{.HelpName}} public s3/public-commons/images
5. Get bucket permissions.
5. Set a prefix to the policy file path on Amazon S3 cloud storage.
$ {{.HelpName}} /path/to/policy.json s3/public-commons/images
6. Get bucket permissions.
$ {{.HelpName}} s3/shared
6. List policies set to a specified bucket.
7. List policies set to a specified bucket.
$ {{.HelpName}} list s3/shared
7. List public object URLs recursively.
8. List public object URLs recursively.
$ {{.HelpName}} --recursive links s3/shared/
`,
@@ -118,6 +129,10 @@ func (s policyMessage) String() string {
return console.Colorize("Policy",
"Access permission for `"+s.Bucket+"`"+" is `"+string(s.Perms)+"`")
}
if s.Operation == "setJSON" {
return console.Colorize("Policy",
"Access permission for `"+s.Bucket+"`"+" is set from `"+string(s.Perms)+"`")
}
// nothing to print
return ""
}
@@ -182,7 +197,7 @@ func checkPolicySyntax(ctx *cli.Context) {
}
default:
if argsLength == 2 {
if argsLength == 2 && filepath.Ext(string(firstArg)) != ".json" {
fatalIf(errDummy().Trace(),
"Unrecognized permission `"+string(firstArg)+"`. Allowed values are [none, download, upload, public].")
}
@@ -212,7 +227,37 @@ func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
return err.Trace(targetURL)
}
policy := accessPermToString(targetPERMS)
if err = clnt.SetAccess(policy); err != nil {
if err = clnt.SetAccess(policy, false); err != nil {
return err.Trace(targetURL, string(targetPERMS))
}
return nil
}
// doSetAccessJSON do set access JSON.
func doSetAccessJSON(targetURL string, targetPERMS accessPerms) *probe.Error {
clnt, err := newClient(targetURL)
if err != nil {
return err.Trace(targetURL)
}
fileReader, e := os.Open(string(targetPERMS))
if e != nil {
fatalIf(probe.NewError(e).Trace(), "Unable to set policy for `"+targetURL+"`.")
}
defer fileReader.Close()
const maxJSONSize = 120 * 1024 // 120KiB
configBuf := make([]byte, maxJSONSize+1)
n, e := io.ReadFull(fileReader, configBuf)
if e == nil {
return probe.NewError(bytes.ErrTooLarge).Trace(targetURL)
}
if e != io.ErrUnexpectedEOF {
return probe.NewError(e).Trace(targetURL)
}
configBytes := configBuf[:n]
if err = clnt.SetAccess(string(configBytes), true); err != nil {
return err.Trace(targetURL, string(targetPERMS))
}
return nil
@@ -343,47 +388,37 @@ func runPolicyLinksCmd(ctx *cli.Context) {
// Run policy cmd to fetch set permission
func runPolicyCmd(ctx *cli.Context) {
var operation string
var probeErr *probe.Error
perms := accessPerms(ctx.Args().First())
targetURL := ctx.Args().Last()
if perms.isValidAccessPERM() {
targetURL := ctx.Args().Last()
err := doSetAccess(targetURL, perms)
// Upon error exit.
if err != nil {
switch err.ToGoError().(type) {
case APINotImplemented:
fatalIf(err.Trace(), "Unable to set policy of a non S3 url `"+targetURL+"`.")
default:
fatalIf(err.Trace(targetURL, string(perms)),
"Unable to set policy `"+string(perms)+"` for `"+targetURL+"`.")
}
}
printMsg(policyMessage{
Status: "success",
Operation: "set",
Bucket: targetURL,
Perms: perms,
})
probeErr = doSetAccess(targetURL, perms)
operation = "set"
} else if perms.isValidAccessFile() {
probeErr = doSetAccessJSON(targetURL, perms)
operation = "setJSON"
} else {
targetURL := ctx.Args().First()
perms, err := doGetAccess(targetURL)
if err != nil {
switch err.ToGoError().(type) {
case APINotImplemented:
fatalIf(err.Trace(), "Unable to get policy of a non S3 url `"+targetURL+"`.")
default:
fatalIf(err.Trace(targetURL), "Unable to get policy for `"+targetURL+"`.")
}
}
printMsg(policyMessage{
Status: "success",
Operation: "get",
Bucket: targetURL,
Perms: perms,
})
targetURL = ctx.Args().First()
perms, probeErr = doGetAccess(targetURL)
operation = "get"
}
// Upon error exit.
if probeErr != nil {
switch probeErr.ToGoError().(type) {
case APINotImplemented:
fatalIf(probeErr.Trace(), "Unable to "+operation+" policy of a non S3 url `"+targetURL+"`.")
default:
fatalIf(probeErr.Trace(targetURL, string(perms)),
"Unable to "+operation+" policy `"+string(perms)+"` for `"+targetURL+"`.")
}
}
printMsg(policyMessage{
Status: "success",
Operation: operation,
Bucket: targetURL,
Perms: perms,
})
}
func mainPolicy(ctx *cli.Context) error {
+13
View File
@@ -809,12 +809,16 @@ Manage anonymous bucket policies to a bucket and its contents
```sh
USAGE:
mc policy [FLAGS] PERMISSION TARGET
mc policy [FLAGS] FILE TARGET
mc policy [FLAGS] TARGET
mc policy list [FLAGS] TARGET
PERMISSION:
Allowed policies are: [none, download, upload, public].
FILE:
A valid S3 policy JSON filepath.
FLAGS:
--help, -h show help
```
@@ -837,6 +841,15 @@ mc policy download play/mybucket/myphotos/2020/
Access permission for ‘play/mybucket/myphotos/2020/’ is set to 'download'
```
*Example : Set anonymous bucket policy from a JSON file*
Configure bucket policy for ``mybucket`` with a policy JSON file.
```sh
mc policy /tmp/policy.json play/mybucket
Access permission for `play/mybucket` is set from `/tmp/policy.json`
```
*Example : Remove current anonymous bucket policy*
Remove any bucket policy for *mybucket/myphotos/2020/* sub-directory.