support session tokens as part of ENV (#3213)

This commit is contained in:
Harshavardhana
2020-05-07 15:21:12 -07:00
committed by GitHub
parent ad0bc4c33d
commit 2e586e6b9d
8 changed files with 154 additions and 163 deletions
+2 -2
View File
@@ -117,7 +117,7 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
}
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey + config.SessionToken))
confSum := confHash.Sum32()
// Lookup previous cache by hash.
@@ -127,7 +127,7 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
var found bool
if api, found = clientCache[confSum]; !found {
// if Signature version '4' use NewV4 directly.
creds := credentials.NewStaticV4(config.AccessKey, config.SecretKey, "")
creds := credentials.NewStaticV4(config.AccessKey, config.SecretKey, config.SessionToken)
// if Signature version '2' use NewV2 directly.
if strings.ToUpper(config.Signature) == "S3V2" {
creds = credentials.NewStaticV2(config.AccessKey, config.SecretKey, "")
+11 -10
View File
@@ -117,16 +117,17 @@ type ClientContent struct {
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
type Config struct {
AccessKey string
SecretKey string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
AccessKey string
SecretKey string
SessionToken string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
}
// SelectObjectOpts - opts entered for select API
+6 -5
View File
@@ -37,11 +37,12 @@ var (
// hostConfig configuration of a host.
type hostConfigV9 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
Lookup string `json:"lookup"`
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
SessionToken string `json:"sessionToken,omitempty"`
API string `json:"api"`
Lookup string `json:"lookup"`
}
// configV8 config version.
+46 -62
View File
@@ -200,73 +200,56 @@ func mustGetHostConfig(alias string) *hostConfigV9 {
return hostCfg
}
var (
hostKeys = regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)$")
hostKeyTokens = regexp.MustCompile("^(https?://)(.*?):(.*?):(.*?)@(.*?)$")
)
// parse url usually obtained from env.
func parseEnvURL(envURL string) (*url.URL, string, string, *probe.Error) {
u, e := url.Parse(envURL)
func parseEnvURLStr(envURL string) (*url.URL, string, string, string, *probe.Error) {
var accessKey, secretKey, sessionToken string
var parsedURL string
if hostKeyTokens.MatchString(envURL) {
parts := hostKeyTokens.FindStringSubmatch(envURL)
if len(parts) != 6 {
return nil, "", "", "", errInvalidArgument().Trace(envURL)
}
accessKey = parts[2]
secretKey = parts[3]
sessionToken = parts[4]
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[5])
} else if hostKeys.MatchString(envURL) {
parts := hostKeys.FindStringSubmatch(envURL)
if len(parts) != 5 {
return nil, "", "", "", errInvalidArgument().Trace(envURL)
}
accessKey = parts[2]
secretKey = parts[3]
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[4])
}
var u *url.URL
var e error
if parsedURL != "" {
u, e = url.Parse(parsedURL)
} else {
u, e = url.Parse(envURL)
}
if e != nil {
return nil, "", "", probe.NewError(e).Trace(envURL)
return nil, "", "", "", probe.NewError(e)
}
var accessKey, secretKey string
// Check if username:password is provided in URL, with no
// access keys or secret we proceed and perform anonymous
// requests.
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
// Look for if URL has invalid values and return error.
if !((u.Scheme == "http" || u.Scheme == "https") &&
(u.Path == "/" || u.Path == "") && u.Opaque == "" &&
!u.ForceQuery && u.RawQuery == "" && u.Fragment == "") {
return nil, "", "", errInvalidArgument().Trace(u.String())
return nil, "", "", "", errInvalidArgument().Trace(u.String())
}
// Now that we have validated the URL to be in expected style.
u.User = nil
return u, accessKey, secretKey, nil
}
// parse url usually obtained from env.
func parseEnvURLStr(envURL string) (*url.URL, string, string, *probe.Error) {
var envURLStr string
u, accessKey, secretKey, err := parseEnvURL(envURL)
if err != nil {
// url parsing can fail when accessKey/secretKey contains non url encoded values
// such as #. Strip accessKey/secretKey from envURL and parse again.
re := regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)$")
res := re.FindAllStringSubmatch(envURL, -1)
// regex will return full match, scheme, accessKey, secretKey and endpoint:port as
// captured groups.
if res == nil || len(res[0]) != 5 {
return nil, "", "", err
}
for k, v := range res[0] {
if k == 2 {
accessKey = v
}
if k == 3 {
secretKey = v
}
if k == 1 || k == 4 {
envURLStr = fmt.Sprintf("%s%s", envURLStr, v)
}
}
u, _, _, err = parseEnvURL(envURLStr)
if err != nil {
return nil, "", "", err
if accessKey == "" && secretKey == "" {
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
}
// Check if username:password is provided in URL, with no
// access keys or secret we proceed and perform anonymous
// requests.
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
return u, accessKey, secretKey, nil
return u, accessKey, secretKey, sessionToken, nil
}
const (
@@ -275,16 +258,17 @@ const (
)
func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
u, accessKey, secretKey, err := parseEnvURLStr(envURL)
u, accessKey, secretKey, sessionToken, err := parseEnvURLStr(envURL)
if err != nil {
return nil, err.Trace(envURL)
}
return &hostConfigV9{
URL: u.String(),
API: "S3v4",
AccessKey: accessKey,
SecretKey: secretKey,
URL: u.String(),
API: "S3v4",
AccessKey: accessKey,
SecretKey: secretKey,
SessionToken: sessionToken,
}, nil
}
+73 -23
View File
@@ -21,11 +21,12 @@ import "testing"
// Tests valid host URL functionality.
func TestParseEnvURLStr(t *testing.T) {
testCases := []struct {
hostURL string
accessKey string
secretKey string
hostname string
port string
hostURL string
accessKey string
secretKey string
sessionToken string
hostname string
port string
}{
{
hostURL: "https://minio:minio1#23@localhost:9000",
@@ -48,30 +49,79 @@ func TestParseEnvURLStr(t *testing.T) {
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://minio:minio123:token@localhost:9000",
accessKey: "minio",
secretKey: "minio123",
sessionToken: "token",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://minio@localhost:9000",
accessKey: "minio",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://minio:@localhost:9000",
accessKey: "minio",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://:@localhost:9000",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://:minio123@localhost:9000",
hostname: "localhost",
secretKey: "minio123",
port: "9000",
},
{
hostURL: "https://:minio123:token@localhost:9000",
hostname: "localhost",
secretKey: "minio123",
sessionToken: "token",
port: "9000",
},
{
hostURL: "https://:minio123:@localhost:9000",
hostname: "localhost",
secretKey: "minio123",
port: "9000",
},
}
for i, testCase := range testCases {
url, ak, sk, err := parseEnvURLStr(testCase.hostURL)
if testCase.accessKey != ak {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.accessKey, ak)
}
if testCase.secretKey != sk {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.secretKey, sk)
}
if testCase.hostname != url.Hostname() {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.hostname, url.Hostname())
}
if testCase.port != url.Port() {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.port, url.Port())
}
if err != nil {
t.Fatalf("Test %d: Expected test to pass. Failed with err %s", i+1, err)
}
for _, testCase := range testCases {
t.Run("", func(t *testing.T) {
url, ak, sk, token, err := parseEnvURLStr(testCase.hostURL)
if testCase.accessKey != ak {
t.Fatalf("Expected %s, got %s", testCase.accessKey, ak)
}
if testCase.secretKey != sk {
t.Fatalf("Expected %s, got %s", testCase.secretKey, sk)
}
if testCase.sessionToken != token {
t.Fatalf("Expected %s, got %s", testCase.sessionToken, token)
}
if testCase.hostname != url.Hostname() {
t.Fatalf("Expected %s, got %s", testCase.hostname, url.Hostname())
}
if testCase.port != url.Port() {
t.Fatalf("Expected %s, got %s", testCase.port, url.Port())
}
if err != nil {
t.Fatalf("Expected test to pass. Failed with err %s", err)
}
})
}
}
func TestParseEnvURLStrInvalid(t *testing.T) {
_, _, _, err := parseEnvURLStr("")
_, _, _, _, err := parseEnvURLStr("")
if err == nil {
t.Fatalf("Expected failure")
}
+1
View File
@@ -146,6 +146,7 @@ func NewS3Config(urlStr string, hostCfg *hostConfigV9) *Config {
if hostCfg != nil {
s3Config.AccessKey = hostCfg.AccessKey
s3Config.SecretKey = hostCfg.SecretKey
s3Config.SessionToken = hostCfg.SessionToken
s3Config.Signature = hostCfg.API
}
s3Config.Lookup = getLookupType(hostCfg.Lookup)
-60
View File
@@ -23,66 +23,6 @@ import (
"github.com/minio/minio-go/v6/pkg/encrypt"
)
func TestParseURLEnv(t *testing.T) {
testCases := []struct {
envURL string
expectedURL string
expectedAccess string
expectedSecret string
success bool
}{
{
envURL: "https://username:password@play.min.io/",
expectedURL: "https://play.min.io/",
expectedAccess: "username",
expectedSecret: "password",
success: true,
},
{
envURL: "https://play.min.io/",
expectedURL: "https://play.min.io/",
success: true,
},
{
envURL: "ftp://play.min.io/",
success: false,
},
{
envURL: "",
success: false,
},
{
envURL: "https://play.min.io/path",
success: false,
},
{
envURL: "https://play.min.io/?path=value",
success: false,
},
}
for i, testCase := range testCases {
u, accessKey, secretKey, err := parseEnvURL(testCase.envURL)
if err != nil && testCase.success {
t.Fatalf("Test %d: Expected success, got %s", i+1, err)
}
if err == nil && !testCase.success {
t.Fatalf("Test %d: Expected error, got success", i+1)
}
if accessKey != testCase.expectedAccess {
t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedAccess, accessKey)
}
if secretKey != testCase.expectedSecret {
t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedSecret, secretKey)
}
if err == nil {
if u.String() != testCase.expectedURL {
t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedURL, u.String())
}
}
}
}
func TestParseEncryptionKeys(t *testing.T) {
sseKey1, err := encrypt.NewSSEC([]byte("32byteslongsecretkeymustbegiven2"))
if err != nil {
+15 -1
View File
@@ -168,7 +168,9 @@ echo -e "BKIKJAA5BMMU2RHO6IBB\nV7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12" | \
mc config host add minio http://192.168.1.51 --api S3v4
```
### Specify host configuration through environment variable
### Specify temporary host configuration through environment variable
#### Static credentials
```
export MC_HOST_<alias>=https://<Access Key>:<Secret Key>@<YOUR-S3-ENDPOINT>
```
@@ -179,6 +181,18 @@ export MC_HOST_myalias=https://Q3AM3UQ867SPQQA43P2F:zuf+tfteSlswRu7BJ86wekitnifI
mc ls myalias
```
#### Rotating credentials
```
export MC_HOST_<alias>=https://<Access Key>:<Secret Key>:<Session Token>@<YOUR-S3-ENDPOINT>
```
Example:
```
export MC_HOST_myalias=https://Q3AM3UQ867SPQQA43P2F:zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG:eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiJOVUlCT1JaWVRWMkhHMkJNUlNYUiIsImF1ZCI6IlBvRWdYUDZ1Vk80NUlzRU5SbmdEWGo1QXU1WWEiLCJhenAiOiJQb0VnWFA2dVZPNDVJc0VOUm5nRFhqNUF1NVlhIiwiZXhwIjoxNTM0ODk2NjI5LCJpYXQiOjE1MzQ4OTMwMjksImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0Ojk0NDMvb2F1dGgyL3Rva2VuIiwianRpIjoiNjY2OTZjZTctN2U1Ny00ZjU5LWI0MWQtM2E1YTMzZGZiNjA4In0.eJONnVaSVHypiXKEARSMnSKgr-2mlC2Sr4fEGJitLcJF_at3LeNdTHv0_oHsv6ZZA3zueVGgFlVXMlREgr9LXA@play.min.io
mc ls myalias
```
## 4. Test Your Setup
`mc` is pre-configured with https://play.min.io, aliased as "play". It is a hosted MinIO server for testing and development purpose. To test Amazon S3, simply replace "play" with "s3" or the alias you used at the time of setup.