From 39d3f1439b6dcbf29918a80f4ecb00147001a691 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 17 Apr 2015 20:03:49 -0700 Subject: [PATCH] Review error messages part of #286 --- aliases.go | 19 +++---- aliases_test.go | 12 ++--- auth.go | 57 +++++++++++++++++++++ cmd-config.go | 9 ++++ cmd-cp.go | 22 ++++---- cmd-ls.go | 7 +-- cmd-mb.go | 2 +- cmd_test.go | 7 +-- notifier.go | 2 +- pkg/config/aliases.go | 24 --------- pkg/config/auth.go | 47 ----------------- pkg/config/config.go | 63 ----------------------- pkg/config/config_test.go | 66 ------------------------ pkg/config/context.go | 103 -------------------------------------- pkg/config/errors.go | 44 ---------------- 15 files changed, 101 insertions(+), 383 deletions(-) create mode 100644 auth.go delete mode 100644 pkg/config/aliases.go delete mode 100644 pkg/config/auth.go delete mode 100644 pkg/config/config.go delete mode 100644 pkg/config/config_test.go delete mode 100644 pkg/config/context.go delete mode 100644 pkg/config/errors.go diff --git a/aliases.go b/aliases.go index f6ab6056..204f8cc7 100644 --- a/aliases.go +++ b/aliases.go @@ -34,17 +34,16 @@ func isValidAliasName(aliasName string) bool { // aliasExpand expands aliased (name:/path) to full URL, used by url-parser func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, err error) { - url, err := url.Parse(aliasedURL) - if err != nil { - // Not a valid URL. Return error - return "", iodine.New(errInvalidURL{url: aliasedURL}, nil) + if aliasedURL == "" || aliases == nil { + return aliasedURL, iodine.New(errInvalidArgument{}, nil) } - - // Not an aliased URL - if url.Scheme == "" { + u, err := url.Parse(aliasedURL) + if err != nil { + return aliasedURL, iodine.New(errInvalidURL{url: aliasedURL}, nil) + } + if u.Scheme == "" { return aliasedURL, nil } - for aliasName, expandedURL := range aliases { if !isValidAliasName(aliasName) { return "", iodine.New(errInvalidAliasName{name: aliasName}, nil) @@ -55,7 +54,5 @@ func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, e return expandedURL + "/" + splits[1], nil } } - - // No matching alias. Return the original - return aliasedURL, nil + return aliasedURL, iodine.New(errAliasNotFound{name: aliasedURL}, nil) } diff --git a/aliases_test.go b/aliases_test.go index 9da9b889..9b071891 100644 --- a/aliases_test.go +++ b/aliases_test.go @@ -43,15 +43,15 @@ func (s *MySuite) TestEmptyExpansions(c *C) { // c.Skip("Test still being written") url, err := aliasExpand("hello", nil) c.Assert(url, Equals, "hello") - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) url, err = aliasExpand("minio://hello", nil) c.Assert(url, Equals, "minio://hello") - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) url, err = aliasExpand("$#\\", nil) c.Assert(url, Equals, "$#\\") - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) url, err = aliasExpand("foo:bar", map[string]string{"foo": "http://foo"}) c.Assert(url, Equals, "http://foo/bar") @@ -59,13 +59,13 @@ func (s *MySuite) TestEmptyExpansions(c *C) { url, err = aliasExpand("myfoo:bar", map[string]string{"foo": "http://foo"}) c.Assert(url, Equals, "myfoo:bar") - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) url, err = aliasExpand("", map[string]string{"foo": "http://foo"}) c.Assert(url, Equals, "") - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) url, err = aliasExpand("hello", nil) c.Assert(url, Equals, "hello") - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) } diff --git a/auth.go b/auth.go new file mode 100644 index 00000000..b4c93214 --- /dev/null +++ b/auth.go @@ -0,0 +1,57 @@ +/* + * Mini Copy, (C) 2015 Minio, Inc. + * + * 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 main + +// exact key length +const ( + accessKeyLength = 20 + secretAccessLength = 40 +) + +// isValidSecretKey - validate secret key +func isValidSecretKey(secretAccesskey string) bool { + if len(secretAccesskey) != secretAccessLength { + return false + } + return true +} + +// isValidAccessKey - validate access key +func isValidAccessKey(accessKeyID string) bool { + if len(accessKeyID) != accessKeyLength { + return false + } + // Is alphanumeric? + isalnum := func(c rune) bool { + return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' + } + for _, char := range accessKeyID { + if isalnum(char) { + continue + } + switch char { + case '-': + case '.': + case '_': + case '~': + continue + default: + return false + } + } + return true +} diff --git a/cmd-config.go b/cmd-config.go index 09a819df..48177eee 100644 --- a/cmd-config.go +++ b/cmd-config.go @@ -238,6 +238,15 @@ func getHostConfig(requestURL string) (map[string]string, error) { return nil, iodine.New(errInvalidGlobURL{glob: globURL, request: requestURL}, nil) } if match { + // verify Auth key validity for all hosts other than localhost + if !strings.Contains(getHostURL(u), "localhost") { + if !isValidAccessKey(hostConfig["Auth.AccessKeyID"]) { + return nil, iodine.New(errInvalidAuthKeys{}, nil) + } + if !isValidSecretKey(hostConfig["Auth.SecretAccessKey"]) { + return nil, iodine.New(errInvalidAuthKeys{}, nil) + } + } return hostConfig, nil } } diff --git a/cmd-cp.go b/cmd-cp.go index 585436a1..ebd4f7d1 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -26,7 +26,6 @@ import ( "github.com/minio-io/minio/pkg/utils/log" ) -// doCopyCmd copies objects into and from a bucket or between buckets func runCopyCmd(ctx *cli.Context) { if len(ctx.Args()) < 2 { cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code @@ -42,27 +41,28 @@ func runCopyCmd(ctx *cli.Context) { urls, err := parseURLs(ctx.Args(), config.GetMapString("Aliases")) if err != nil { log.Debug.Println(iodine.New(err, nil)) - console.Fatalln("mc: Unable to parse URL") + console.Fatalf("mc: Unable to parse URLs [%s]\n", urls) } sourceURL := urls[0] // First arg is source targetURLs := urls[1:] // 1 or more targets // perform copy + if ctx.Bool("recursive") { doCopyCmdRecursive(mcClientManager{}, sourceURL, targetURLs) - } else { - humanReadableError, err := doCopyCmd(mcClientManager{}, sourceURL, targetURLs) - err = iodine.New(err, nil) - if err != nil { - if humanReadableError == "" { - humanReadableError = "No error message present, please rerun with --debug and report a bug." - } - log.Debug.Println(err) - console.Errorln("mc: " + humanReadableError) + } + humanReadableError, err := doCopyCmd(mcClientManager{}, sourceURL, targetURLs) + err = iodine.New(err, nil) + if err != nil { + if humanReadableError == "" { + humanReadableError = "No error message present, please rerun with --debug and report a bug." } + log.Debug.Println(err) + console.Errorf("mc: %s\n", humanReadableError) } } +// doCopyCmd copies objects into and from a bucket or between buckets func doCopyCmd(manager clientManager, sourceURL string, targetURLs []string) (string, error) { reader, length, hexMd5, err := manager.getSourceReader(sourceURL) if err != nil { diff --git a/cmd-ls.go b/cmd-ls.go index 4398b9e9..8b51d77a 100644 --- a/cmd-ls.go +++ b/cmd-ls.go @@ -69,7 +69,7 @@ func doListCmd(ctx *cli.Context) { u, err := parseURL(arg, config.GetMapString("Aliases")) if err != nil { log.Debug.Println(iodine.New(err, nil)) - console.Fatalln("mc: Unable to parse URL") + console.Fatalf("mc: Unable to parse URL [%s]\n", u) } manager := mcClientManager{} clnt, err := manager.getNewClient(u, globalDebugFlag) @@ -104,14 +104,15 @@ func doListCmd(ctx *cli.Context) { for r := retries.init(); r.retry(); { items, err = clnt.ListObjects(bucket, object) - if !isValidRetry(err) { break } } if err != nil { log.Debug.Println(iodine.New(err, nil)) - console.Fatalf("mc: Unable to list objects for URL[%s] ", u) + // Add a newline + console.Infoln() + console.Fatalf("mc: Unable to list objects for URL [%s]\n", u) } console.Infoln() printObjects(items) diff --git a/cmd-mb.go b/cmd-mb.go index 4cc0a7fb..c666768d 100644 --- a/cmd-mb.go +++ b/cmd-mb.go @@ -38,7 +38,7 @@ func doMakeBucketCmd(ctx *cli.Context) { u, err := parseURL(arg, config.GetMapString("Aliases")) if err != nil { log.Debug.Println(iodine.New(err, nil)) - console.Fatalf("mc: Unable to parse URL[%s]\n", u) + console.Fatalf("mc: Unable to parse URL [%s]\n", u) } bucket, _, err := url2Object(u) if err != nil { diff --git a/cmd_test.go b/cmd_test.go index 78e03844..54ac969c 100644 --- a/cmd_test.go +++ b/cmd_test.go @@ -23,6 +23,7 @@ import ( "sync" "errors" + . "github.com/minio-io/check" "github.com/minio-io/mc/pkg/client" @@ -36,7 +37,7 @@ var _ = Suite(&CmdTestSuite{}) func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) { manager := &MockclientManager{} sourceURL, err := parseURL("foo", nil) - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) data := "Hello World" md5Sum := md5.Sum([]byte(data)) @@ -44,7 +45,7 @@ func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) { dataLength := int64(len(data)) targetURL, err := parseURL("bar", nil) - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) targetURLs := []string{targetURL} sourceReader, sourceWriter := io.Pipe() @@ -65,7 +66,7 @@ func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) { manager.On("getTargetWriter", targetURL, hexMd5, dataLength).Return(targetWriter, nil).Once() doCopyCmd(manager, sourceURL, targetURLs) wg.Wait() - c.Assert(err, IsNil) + c.Assert(err, Not(IsNil)) c.Assert(resultBuffer.String(), DeepEquals, data) } diff --git a/notifier.go b/notifier.go index b81e9efd..73bf4201 100644 --- a/notifier.go +++ b/notifier.go @@ -1,5 +1,5 @@ /* - * Mini Copy, (C) 2014, 2015 Minio, Inc. + * Mini Copy, (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/pkg/config/aliases.go b/pkg/config/aliases.go deleted file mode 100644 index 9b39aacf..00000000 --- a/pkg/config/aliases.go +++ /dev/null @@ -1,24 +0,0 @@ -package config - -// Aliases - keep a map -type Aliases map[string]string - -// Set - set an alias -func (a Aliases) Set(aliasName, urlName string) { - a[aliasName] = urlName -} - -// Get - get an alias -func (a Aliases) Get(aliasName string) string { - return a[aliasName] -} - -// IsExists verify if alias exists -func (a Aliases) IsExists(aliasName string) bool { - for alias := range a { - if alias == aliasName { - return true - } - } - return false -} diff --git a/pkg/config/auth.go b/pkg/config/auth.go deleted file mode 100644 index 85056ab6..00000000 --- a/pkg/config/auth.go +++ /dev/null @@ -1,47 +0,0 @@ -package config - -// Auth - authorization keys -type Auth struct { - AccessKeyID string - SecretAccessKey string -} - -// exact key length -const ( - AccessKeyLength = 20 - SecretAccessLength = 40 -) - -// IsValidSecretKey - validate secret key -func (a Auth) IsValidSecretKey() bool { - if len(a.SecretAccessKey) != SecretAccessLength { - return false - } - return true -} - -// IsValidAccessKey - validate access key -func (a Auth) IsValidAccessKey() bool { - if len(a.AccessKeyID) != AccessKeyLength { - return false - } - // Is alphanumeric? - isalnum := func(c rune) bool { - return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' - } - for _, char := range a.AccessKeyID { - if isalnum(char) { - continue - } - switch char { - case '-': - case '.': - case '_': - case '~': - continue - default: - return false - } - } - return true -} diff --git a/pkg/config/config.go b/pkg/config/config.go deleted file mode 100644 index 1a8386ed..00000000 --- a/pkg/config/config.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Mini Copy, (C) 2015 Minio, Inc. - * - * 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 config - -import "github.com/minio-io/minio/pkg/iodine" - -// Config - configuration -type Config struct { - Version uint // Config version - Hosts map[string]Auth // URL and their respective Auth map - Aliases Aliases // aliasName and URL map -} - -// AddAlias - add a alias into existing alias list -func (c *Config) AddAlias(aliasName string, aliasURL string) error { - if c.Aliases.IsExists(aliasName) { - return iodine.New(AliasExists{Name: aliasName}, nil) - } - c.Aliases.Set(aliasName, aliasURL) - return nil -} - -// HostExists - check if host exists -func (c *Config) HostExists(hostURL string) bool { - for host := range c.Hosts { - if host == hostURL { - return true - } - } - return false -} - -// AddHostAuth - add host authorization -func (c *Config) AddHostAuth(hostURL, accessKeyID, secretAccessKey string) error { - if c.HostExists(hostURL) { - return iodine.New(HostExists{Name: hostURL}, nil) - } - auth := Auth{ - AccessKeyID: accessKeyID, - SecretAccessKey: secretAccessKey, - } - if !auth.IsValidAccessKey() || !auth.IsValidSecretKey() { - return iodine.New(InvalidAuthKeys{}, nil) - } - c.Aliases = make(Aliases) - c.Hosts = make(map[string]Auth) - c.Hosts[hostURL] = auth - return nil -} diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go deleted file mode 100644 index 684efeea..00000000 --- a/pkg/config/config_test.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Mini Copy, (C) 2015 Minio, Inc. - * - * 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 config - -import ( - "io/ioutil" - "os" - "testing" - - . "github.com/minio-io/check" -) - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -func Test(t *testing.T) { TestingT(t) } - -func (s *MySuite) TestConfig(c *C) { - // create new config.json - configPath, _ := ioutil.TempDir("/tmp", "minio-test-") - ctx, err := New(configPath, "config.json") - c.Assert(err, IsNil) - defer os.RemoveAll(configPath) - - // initialize config - ctx.Config = new(Config) - - // error on invalid auth keys - err = ctx.Config.AddHostAuth("http*://s3*.amazonaws.com", "YOUR-ACCESS-KEY-ID-HERE", "YOUR-SECRET-ACCESS-KEY-HERE") - c.Assert(err, Not(IsNil)) - - // success on valid auth keys - err = ctx.Config.AddHostAuth("http*://s3*.amazonaws.com", "AC5NH40NQLTL4D2W92PM", "0nAMx5oJbWx5IgCmOJJneXM8w/ohTz2b0QAb2xvN") - c.Assert(err, IsNil) - - // success on add new alias - err = ctx.Config.AddAlias("s3", "https://s3.amazonaws.com") - c.Assert(err, IsNil) - - // error on duplicate alias - err = ctx.Config.AddAlias("s3", "https://s3.amazonaws.com") - c.Assert(err, Not(IsNil)) - - // save config - err = ctx.SaveConfig() - c.Assert(err, IsNil) - - // load config - err = ctx.LoadConfig() - c.Assert(err, IsNil) -} diff --git a/pkg/config/context.go b/pkg/config/context.go deleted file mode 100644 index a94d7fd1..00000000 --- a/pkg/config/context.go +++ /dev/null @@ -1,103 +0,0 @@ -package config - -import ( - "encoding/json" - "io" - "os" - "path" - "strings" - "sync" - - "github.com/minio-io/minio/pkg/iodine" -) - -// Context - config context -type Context struct { - // copy of Config - Config *Config - - // file and path for config - configFile string - configPath string - - // lock - lock *sync.RWMutex -} - -// GetConfigPath path to config file -func (c *Context) GetConfigPath() string { - return c.configPath -} - -// GetConfigFile config file -func (c *Context) GetConfigFile() string { - return c.configFile -} - -// SaveConfig - write encoded json in config file -func (c *Context) SaveConfig() error { - c.lock.Lock() - defer c.lock.Unlock() - - var file *os.File - var err error - - file, err = os.OpenFile(c.configFile, os.O_WRONLY, 0666) - defer file.Close() - if err != nil { - return iodine.New(err, nil) - } - - encoder := json.NewEncoder(file) - encoder.Encode(c.Config) - return nil -} - -// LoadConfig - read json config file and decode -func (c *Context) LoadConfig() error { - c.lock.RLock() - defer c.lock.RUnlock() - - var file *os.File - var err error - - file, err = os.OpenFile(c.configFile, os.O_RDONLY, 0666) - defer file.Close() - if err != nil { - return iodine.New(err, nil) - } - - config := new(Config) - decoder := json.NewDecoder(file) - err = decoder.Decode(&config) - switch err { - case io.EOF: - return nil - case nil: - c.Config = config - return nil - default: - return iodine.New(err, nil) - } -} - -// New - instantiate a new config context -func New(configPath, configFileName string) (*Context, error) { - if configPath == "" || strings.TrimSpace(configPath) == "" { - return nil, iodine.New(InvalidArgument{}, nil) - } - if configFileName == "" || strings.TrimSpace(configFileName) == "" { - return nil, iodine.New(InvalidArgument{}, nil) - } - c := new(Context) - c.configPath = configPath - c.configFile = path.Join(c.configPath, configFileName) - if _, err := os.Stat(c.configFile); os.IsNotExist(err) { - _, err = os.Create(c.configFile) - if err != nil { - return nil, iodine.New(err, nil) - } - } - c.lock = new(sync.RWMutex) - return c, nil -} diff --git a/pkg/config/errors.go b/pkg/config/errors.go deleted file mode 100644 index a8f7a245..00000000 --- a/pkg/config/errors.go +++ /dev/null @@ -1,44 +0,0 @@ -package config - -import "fmt" - -// AliasExists - alias exists -type AliasExists struct { - Name string -} - -func (e AliasExists) Error() string { - return fmt.Sprintf("alias: %s exists", e.Name) -} - -// AliasNotFound - alias not found -type AliasNotFound struct { - Name string -} - -func (e AliasNotFound) Error() string { - return fmt.Sprintf("alias: %s exists", e.Name) -} - -// InvalidAuthKeys - invalid authorization keys -type InvalidAuthKeys struct{} - -func (e InvalidAuthKeys) Error() string { - return fmt.Sprintf("invalid authorization key") -} - -// HostExists - host exists -type HostExists struct { - Name string -} - -func (e HostExists) Error() string { - return fmt.Sprintf("host: %s exists", e.Name) -} - -// InvalidArgument - invalid argument -type InvalidArgument struct{} - -func (e InvalidArgument) Error() string { - return fmt.Sprintf("invalid argument") -}