From 5f4d89ccd56b94d9d69c941818e77be0c5a3854b Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 17 Apr 2015 19:42:32 -0700 Subject: [PATCH 1/2] Deprecate bash-completion support --- aliases.go | 4 +-- cmd-common.go | 17 +----------- cmd-common_test.go | 11 -------- cmd-config.go | 68 +++++++++++++++------------------------------- cmd-options.go | 25 ++--------------- errors.go | 35 ++++++++++++++++++++++-- main.go | 1 - 7 files changed, 60 insertions(+), 101 deletions(-) diff --git a/aliases.go b/aliases.go index dfcaa512..f6ab6056 100644 --- a/aliases.go +++ b/aliases.go @@ -37,7 +37,7 @@ func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, e url, err := url.Parse(aliasedURL) if err != nil { // Not a valid URL. Return error - return "", iodine.New(errInvalidURL{aliasedURL}, nil) + return "", iodine.New(errInvalidURL{url: aliasedURL}, nil) } // Not an aliased URL @@ -47,7 +47,7 @@ func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, e for aliasName, expandedURL := range aliases { if !isValidAliasName(aliasName) { - return "", iodine.New(errInvalidAliasName{alias: aliasName}, nil) + return "", iodine.New(errInvalidAliasName{name: aliasName}, nil) } if strings.HasPrefix(aliasedURL, aliasName) { // Match found. Expand it. diff --git a/cmd-common.go b/cmd-common.go index b67bd949..795dcc0d 100644 --- a/cmd-common.go +++ b/cmd-common.go @@ -18,7 +18,6 @@ package main import ( "net/url" - "path" "time" "io" @@ -47,19 +46,6 @@ func startBar(size int64) *pb.ProgressBar { return bar } -func getMcBashCompletionFilename() (string, error) { - configDir, err := getMcConfigDir() - if err != nil { - return "", err - } - return path.Join(configDir, "mc.bash_completion"), nil -} - -func mustGetMcBashCompletionFilename() string { - p, _ := getMcBashCompletionFilename() - return p -} - type clientManager interface { getSourceReader(urlStr string) (reader io.ReadCloser, length int64, md5hex string, err error) getTargetWriter(urlStr string, md5Hex string, length int64) (io.WriteCloser, error) @@ -104,8 +90,7 @@ func (manager mcClientManager) getTargetWriter(urlStr string, md5Hex string, len return targetClnt.Put(bucket, object, md5Hex, length) } -// getNewClient gets a new client -// TODO refactor this to be more testable +// getNewClient gives a new client interface func (manager mcClientManager) getNewClient(urlStr string, debug bool) (clnt client.Client, err error) { u, err := url.Parse(urlStr) if err != nil { diff --git a/cmd-common_test.go b/cmd-common_test.go index 3819d863..3678efcb 100644 --- a/cmd-common_test.go +++ b/cmd-common_test.go @@ -17,7 +17,6 @@ package main import ( - "strings" "time" "github.com/cheggaaa/pb" @@ -35,13 +34,3 @@ func (s *MySuite) TestStatusBar(c *C) { c.Assert(bar.NotPrint, Equals, true) c.Assert(bar.ShowSpeed, Equals, true) } - -func (s *MySuite) TestBashCompletionFilename(c *C) { - file, err := getMcBashCompletionFilename() - c.Assert(err, IsNil) - c.Assert(file, Not(Equals), "mc.bash_completion") - c.Assert(strings.HasSuffix(file, "mc.bash_completion"), Equals, true) - - file2 := mustGetMcBashCompletionFilename() - c.Assert(file, Equals, file2) -} diff --git a/cmd-config.go b/cmd-config.go index 7a7017b1..09a819df 100644 --- a/cmd-config.go +++ b/cmd-config.go @@ -17,7 +17,6 @@ package main import ( - "bytes" "net/url" "os" "path" @@ -141,11 +140,21 @@ func writeConfig(config qdb.Store) error { func saveConfig(ctx *cli.Context) error { switch ctx.Args().Get(0) { case "generate": - err := writeConfig(generateNewConfig()) + if isMcConfigExist() { + return iodine.New(errConfigExists{}, nil) + } + err := writeConfig(newConfig()) if err != nil { return iodine.New(err, nil) } return nil + case "check": + // verify if the binary can load config file + configStore, err := getMcConfig() + if err != nil || configStore == nil { + return iodine.New(err, nil) + } + return nil default: configStore, err := parseConfigInput(ctx) if err != nil { @@ -155,9 +164,8 @@ func saveConfig(ctx *cli.Context) error { } } -func generateNewConfig() (config qdb.Store) { +func newConfig() (config qdb.Store) { configStore := qdb.NewStore(mcCurrentConfigVersion) - s3Auth := make(map[string]string) localAuth := make(map[string]string) @@ -192,12 +200,15 @@ func parseConfigInput(ctx *cli.Context) (config qdb.Store, err error) { aliasName := alias[0] url := strings.TrimSuffix(alias[1], "/") if strings.HasPrefix(aliasName, "http") { - return nil, iodine.New(errInvalidAliasName{alias: aliasName}, nil) + return nil, iodine.New(errInvalidAliasName{name: aliasName}, nil) } if !strings.HasPrefix(url, "http") { return nil, iodine.New(errInvalidURL{url: url}, nil) } aliases := configStore.GetMapString("Aliases") + if _, ok := aliases[aliasName]; ok { + return nil, iodine.New(errAliasExists{name: aliasName}, nil) + } aliases[aliasName] = url configStore.SetMapString("Aliases", aliases) return configStore, nil @@ -233,8 +244,8 @@ func getHostConfig(requestURL string) (map[string]string, error) { return nil, iodine.New(errNoMatchingHost{}, nil) } -// saveConfigCmd writes config file to disk -func saveConfigCmd(ctx *cli.Context) { +// doConfigCmd is the handler for "mc config" sub-command. +func doConfigCmd(ctx *cli.Context) { // show help if nothing is set if len(ctx.Args()) < 1 && !ctx.IsSet("completion") && !ctx.IsSet("alias") { cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code @@ -245,49 +256,14 @@ func saveConfigCmd(ctx *cli.Context) { console.Fatalln("mc: Unable to identify config file path") } err = saveConfig(ctx) - if os.IsExist(iodine.ToError(err)) { + switch iodine.ToError(err).(type) { + case errConfigExists: log.Debug.Println(iodine.New(err, nil)) console.Fatalln("mc: Configuration file " + configPath + " already exists") - } - if err != nil { + default: + // unexpected error log.Debug.Println(iodine.New(err, nil)) console.Fatalln("mc: Unable to generate config file", configPath) } console.Infoln("mc: Configuration written to " + configPath + ". Please update your access credentials.") } - -// doConfigCmd is the handler for "mc config" sub-command. -func doConfigCmd(ctx *cli.Context) { - // treat bash completion separately here - switch true { - case ctx.Bool("completion") == true: - var b bytes.Buffer - if os.Getenv("SHELL") != "/bin/bash" { - console.Fatalln("mc: Unsupported shell for bash completion detected.. exiting") - } - b.WriteString(mcBashCompletion) - f, err := getMcBashCompletionFilename() - if err != nil { - log.Debug.Println(iodine.New(err, nil)) - console.Fatalln("mc: Unable to identify bash completion path") - } - fl, err := os.OpenFile(f, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) - defer fl.Close() - if err != nil { - log.Debug.Println(iodine.New(err, nil)) - console.Fatalln("mc: Unable to create bash completion file") - } - _, err = fl.Write(b.Bytes()) - if err != nil { - log.Debug.Println(iodine.New(err, nil)) - console.Fatalln("mc: Unable to write to bash completion file") - } - msg := "\nConfiguration written to " + f - msg = msg + "\n\n$ source ${HOME}/.mc/mc.bash_completion\n" - msg = msg + "$ echo 'source ${HOME}/.mc/mc.bash_completion' >> ${HOME}/.bashrc" - console.Infoln(msg) - default: - // rest of the arguments get passed down - saveConfigCmd(ctx) - } -} diff --git a/cmd-options.go b/cmd-options.go index 8146cf82..751973ea 100644 --- a/cmd-options.go +++ b/cmd-options.go @@ -152,10 +152,6 @@ EXAMPLES: Name: "alias", Usage: "Add URL aliases into config", }, - cli.BoolFlag{ - Name: "completion", - Usage: "Generate bash completion \"" + mustGetMcBashCompletionFilename() + "\" file.", - }, }, CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} @@ -173,8 +169,8 @@ EXAMPLES: 1. Generate mc config $ mc config generate - 2. Generate bash completion - $ mc config --completion + 2. Verify configuration + $ mc config check 3. Add alias URLs $ mc config --alias "zek https://s3.amazonaws.com/" @@ -229,20 +225,3 @@ var ( }, } ) - -var ( - mcBashCompletion = `#!/bin/bash - -_mc_completion() { - local cur prev opts base - COMPREPLY=() - cur="${COMP_WORDS[COMP_CWORD]}" - prev="${COMP_WORDS[COMP_CWORD-1]}" - opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion ) - COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) - return 0 -} - -complete -F _mc_completion mc -` -) diff --git a/errors.go b/errors.go index f9442635..8302e608 100644 --- a/errors.go +++ b/errors.go @@ -50,11 +50,11 @@ func (e errInvalidGlobURL) Error() string { } type errInvalidAliasName struct { - alias string + name string } func (e errInvalidAliasName) Error() string { - return "Not a valid alias name: " + e.alias + " Valid examples are: Area51, Grand-Nagus.." + return "Not a valid alias name: " + e.name + " Valid examples are: Area51, Grand-Nagus.." } type errInvalidAuth struct{} @@ -68,3 +68,34 @@ type errNoMatchingHost struct{} func (e errNoMatchingHost) Error() string { return "No matching host found." } + +type errConfigExists struct{} + +func (e errConfigExists) Error() string { + return "Config exists" +} + +// errAliasExists - alias exists +type errAliasExists struct { + name string +} + +func (e errAliasExists) Error() string { + return fmt.Sprintf("alias: %s exists", e.name) +} + +// errAliasNotFound - alias not found +type errAliasNotFound struct { + name string +} + +func (e errAliasNotFound) Error() string { + return fmt.Sprintf("alias: %s exists", e.name) +} + +// errInvalidAuthKeys - invalid authorization keys +type errInvalidAuthKeys struct{} + +func (e errInvalidAuthKeys) Error() string { + return fmt.Sprintf("invalid authorization keys") +} diff --git a/main.go b/main.go index 96e442f3..8af0c242 100644 --- a/main.go +++ b/main.go @@ -86,7 +86,6 @@ func main() { app.Commands = options app.Flags = flags app.Author = "Minio.io" - app.EnableBashCompletion = false app.Before = func(ctx *cli.Context) error { globalQuietFlag = ctx.GlobalBool("quiet") globalDebugFlag = ctx.GlobalBool("debug") From 39d3f1439b6dcbf29918a80f4ecb00147001a691 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 17 Apr 2015 20:03:49 -0700 Subject: [PATCH 2/2] 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") -}