Bläddra i källkod

modify CredentialInf according to the review comments

taowei.wtw 6 år sedan
förälder
incheckning
a77e2a55be
6 ändrade filer med 133 tillägg och 75 borttagningar
  1. 17 12
      oss/auth.go
  2. 5 3
      oss/client.go
  3. 33 0
      oss/client_test.go
  4. 58 48
      oss/conf.go
  5. 15 11
      oss/conn.go
  6. 5 1
      oss/conn_test.go

+ 17 - 12
oss/auth.go

@@ -22,14 +22,17 @@ type headerSorter struct {
 
 // signHeader signs the header and sets it as the authorization header.
 func (conn Conn) signHeader(req *http.Request, canonicalizedResource string) {
+
+	akIf := conn.config.GetCredentialInf()
+
 	// Get the final authorization string
-	authorizationStr := "OSS " + conn.config.GetAccessKeyID() + ":" + conn.getSignedStr(req, canonicalizedResource)
+	authorizationStr := "OSS " + akIf.GetAccessKeyID() + ":" + conn.getSignedStr(req, canonicalizedResource, akIf.GetAccessKeySecret())
 
 	// Give the parameter "Authorization" value
 	req.Header.Set(HTTPHeaderAuthorization, authorizationStr)
 }
 
-func (conn Conn) getSignedStr(req *http.Request, canonicalizedResource string) string {
+func (conn Conn) getSignedStr(req *http.Request, canonicalizedResource string, keySecret string) string {
 	// Find out the "x-oss-"'s address in header of the request
 	temp := make(map[string]string)
 
@@ -58,24 +61,26 @@ func (conn Conn) getSignedStr(req *http.Request, canonicalizedResource string) s
 	signStr := req.Method + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource
 
 	// convert sign to log for easy to view
-	var signBuf bytes.Buffer
-	for i := 0; i < len(signStr); i++ {
-		if signStr[i] != '\n' {
-			signBuf.WriteByte(signStr[i])
-		} else {
-			signBuf.WriteString("\\n")
+	if conn.config.LogLevel >= Debug {
+		var signBuf bytes.Buffer
+		for i := 0; i < len(signStr); i++ {
+			if signStr[i] != '\n' {
+				signBuf.WriteByte(signStr[i])
+			} else {
+				signBuf.WriteString("\\n")
+			}
 		}
+		conn.config.WriteLog(Debug, "[Req:%p]signStr:%s\n", req, signBuf.String())
 	}
-	conn.config.WriteLog(Debug, "[Req:%p]signStr:%s\n", req, signBuf.String())
 
-	h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(conn.config.GetAccessKeySecret()))
+	h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(keySecret))
 	io.WriteString(h, signStr)
 	signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
 
 	return signedStr
 }
 
-func (conn Conn) getRtmpSignedStr(bucketName, channelName, playlistName string, expiration int64, params map[string]interface{}) string {
+func (conn Conn) getRtmpSignedStr(bucketName, channelName, playlistName string, expiration int64, keySecret string, params map[string]interface{}) string {
 	if params[HTTPParamAccessKeyID] == nil {
 		return ""
 	}
@@ -97,7 +102,7 @@ func (conn Conn) getRtmpSignedStr(bucketName, channelName, playlistName string,
 	expireStr := strconv.FormatInt(expiration, 10)
 	signStr := expireStr + "\n" + canonParamsStr + canonResource
 
-	h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(conn.config.GetAccessKeySecret()))
+	h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(keySecret))
 	io.WriteString(h, signStr)
 	signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
 	return signedStr

+ 5 - 3
oss/client.go

@@ -46,6 +46,9 @@ func New(endpoint, accessKeyID, accessKeySecret string, options ...ClientOption)
 	config.AccessKeyID = accessKeyID
 	config.AccessKeySecret = accessKeySecret
 
+	defAkBuild := &defaultCredentialInfBuild{config: config}
+	config.UserAKBuild = defAkBuild
+
 	// URL parse
 	url := &urlMaker{}
 	url.Init(config.Endpoint, config.IsCname, config.IsUseProxy)
@@ -1275,12 +1278,11 @@ func SetLogger(Logger *log.Logger) ClientOption {
 	}
 }
 
-//
 // SetAKInterface sets funciton for get the user's ak
 //
-func SetAKInterface(akIf AKInterface) ClientOption {
+func SetCredentialInfBuild(akBuild CredentialInfBuild) ClientOption {
 	return func(client *Client) {
-		client.Config.UserAKInf = akIf
+		client.Config.UserAKBuild = akBuild
 	}
 }
 

+ 33 - 0
oss/client_test.go

@@ -2712,3 +2712,36 @@ func struct2string(obj interface{}, c *C) string {
 	c.Assert(err, IsNil)
 	return string(str)
 }
+
+type TestCredentialInf struct {
+}
+
+func (testCreInf *TestCredentialInf) GetAccessKeyID() string {
+	return os.Getenv("OSS_TEST_ACCESS_KEY_ID")
+}
+
+func (testCreInf *TestCredentialInf) GetAccessKeySecret() string {
+	return os.Getenv("OSS_TEST_ACCESS_KEY_SECRET")
+}
+
+func (testCreInf *TestCredentialInf) GetSecurityToken() string {
+	return ""
+}
+
+type TestCredentialInfBuild struct {
+}
+
+func (testInfBuild *TestCredentialInfBuild) GetCredentialInf() CredentialInf {
+	return &TestCredentialInf{}
+}
+
+func (s *OssClientSuite) TestClientCredentialInfBuild(c *C) {
+	var bucketNameTest = bucketNamePrefix + randLowStr(6)
+	var defaultBuild TestCredentialInfBuild
+	client, err := New(endpoint, "", "", SetCredentialInfBuild(&defaultBuild))
+	c.Assert(err, IsNil)
+	err = client.CreateBucket(bucketNameTest)
+	c.Assert(err, IsNil)
+	err = client.DeleteBucket(bucketNameTest)
+	c.Assert(err, IsNil)
+}

+ 58 - 48
oss/conf.go

@@ -35,39 +35,68 @@ type HTTPMaxConns struct {
 	MaxIdleConnsPerHost int
 }
 
-// AKInterface is interface for getting AccessKeyID, AccessKeySecret, SecurityToken
-type AKInterface interface {
+// CredentialInf is interface for get AccessKeyID,AccessKeySecret,SecurityToken
+type CredentialInf interface {
 	GetAccessKeyID() string
 	GetAccessKeySecret() string
 	GetSecurityToken() string
 }
 
+// CredentialInfBuild is interface for get CredentialInf
+type CredentialInfBuild interface {
+	GetCredentialInf() CredentialInf
+}
+
+type defaultCredentialInf struct {
+	config *Config
+}
+
+func (defCre *defaultCredentialInf) GetAccessKeyID() string {
+	return defCre.config.AccessKeyID
+}
+
+func (defCre *defaultCredentialInf) GetAccessKeySecret() string {
+	return defCre.config.AccessKeySecret
+}
+
+func (defCre *defaultCredentialInf) GetSecurityToken() string {
+	return defCre.config.SecurityToken
+}
+
+type defaultCredentialInfBuild struct {
+	config *Config
+}
+
+func (defBuild *defaultCredentialInfBuild) GetCredentialInf() CredentialInf {
+	return &defaultCredentialInf{config: defBuild.config}
+}
+
 // Config defines oss configuration
 type Config struct {
-	Endpoint         string       // OSS endpoint
-	AccessKeyID      string       // AccessId
-	AccessKeySecret  string       // AccessKey
-	RetryTimes       uint         // Retry count by default it's 5.
-	UserAgent        string       // SDK name/version/system information
-	IsDebug          bool         // Enable debug mode. Default is false.
-	Timeout          uint         // Timeout in seconds. By default it's 60.
-	SecurityToken    string       // STS Token
-	IsCname          bool         // If cname is in the endpoint.
-	HTTPTimeout      HTTPTimeout  // HTTP timeout
-	HTTPMaxConns     HTTPMaxConns // Http max connections
-	IsUseProxy       bool         // Flag of using proxy.
-	ProxyHost        string       // Flag of using proxy host.
-	IsAuthProxy      bool         // Flag of needing authentication.
-	ProxyUser        string       // Proxy user
-	ProxyPassword    string       // Proxy password
-	IsEnableMD5      bool         // Flag of enabling MD5 for upload.
-	MD5Threshold     int64        // Memory footprint threshold for each MD5 computation (16MB is the default), in byte. When the data is more than that, temp file is used.
-	IsEnableCRC      bool         // Flag of enabling CRC for upload.
-	LogLevel         int          // Log level
-	Logger           *log.Logger  // For write log
-	UploadLimitSpeed int          // Upload limit speed:KB/s, 0 is unlimited
-	UploadLimiter    *OssLimiter  // Bandwidth limit reader for upload
-	UserAKInf        AKInterface  // User provides interface to get AccessKeyID, AccessKeySecret, SecurityToken
+	Endpoint         string             // OSS endpoint
+	AccessKeyID      string             // AccessId
+	AccessKeySecret  string             // AccessKey
+	RetryTimes       uint               // Retry count by default it's 5.
+	UserAgent        string             // SDK name/version/system information
+	IsDebug          bool               // Enable debug mode. Default is false.
+	Timeout          uint               // Timeout in seconds. By default it's 60.
+	SecurityToken    string             // STS Token
+	IsCname          bool               // If cname is in the endpoint.
+	HTTPTimeout      HTTPTimeout        // HTTP timeout
+	HTTPMaxConns     HTTPMaxConns       // Http max connections
+	IsUseProxy       bool               // Flag of using proxy.
+	ProxyHost        string             // Flag of using proxy host.
+	IsAuthProxy      bool               // Flag of needing authentication.
+	ProxyUser        string             // Proxy user
+	ProxyPassword    string             // Proxy password
+	IsEnableMD5      bool               // Flag of enabling MD5 for upload.
+	MD5Threshold     int64              // Memory footprint threshold for each MD5 computation (16MB is the default), in byte. When the data is more than that, temp file is used.
+	IsEnableCRC      bool               // Flag of enabling CRC for upload.
+	LogLevel         int                // Log level
+	Logger           *log.Logger        // For write log
+	UploadLimitSpeed int                // Upload limit speed:KB/s, 0 is unlimited
+	UploadLimiter    *OssLimiter        // Bandwidth limit reader for upload
+	UserAKBuild      CredentialInfBuild // User provides interface to get AccessKeyID, AccessKeySecret, SecurityToken
 }
 
 // LimitUploadSpeed uploadSpeed:KB/s, 0 is unlimited,default is 0
@@ -100,28 +129,9 @@ func (config *Config) WriteLog(LogLevel int, format string, a ...interface{}) {
 	config.Logger.Printf("%s", logBuffer.String())
 }
 
-// for get AccessKeyID
-func (config *Config) GetAccessKeyID() string {
-	if config.UserAKInf != nil {
-		return config.UserAKInf.GetAccessKeyID()
-	}
-	return config.AccessKeyID
-}
-
-// for get AccessKeySecret
-func (config *Config) GetAccessKeySecret() string {
-	if config.UserAKInf != nil {
-		return config.UserAKInf.GetAccessKeySecret()
-	}
-	return config.AccessKeySecret
-}
-
-// for get SecurityToken
-func (config *Config) GetSecurityToken() string {
-	if config.UserAKInf != nil {
-		return config.UserAKInf.GetSecurityToken()
-	}
-	return config.SecurityToken
+// for get CredentialInfBuild
+func (config *Config) GetCredentialInf() CredentialInf {
+	return config.UserAKBuild.GetCredentialInf()
 }
 
 // getDefaultOssConfig gets the default configuration.

+ 15 - 11
oss/conn.go

@@ -239,8 +239,10 @@ func (conn Conn) doRequest(method string, uri *url.URL, canonicalizedResource st
 	req.Header.Set(HTTPHeaderDate, date)
 	req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
 	req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
-	if conn.config.GetSecurityToken() != "" {
-		req.Header.Set(HTTPHeaderOssSecurityToken, conn.config.GetSecurityToken())
+
+	akIf := conn.config.GetCredentialInf()
+	if akIf.GetSecurityToken() != "" {
+		req.Header.Set(HTTPHeaderOssSecurityToken, akIf.GetSecurityToken())
 	}
 
 	if headers != nil {
@@ -281,8 +283,9 @@ func (conn Conn) doRequest(method string, uri *url.URL, canonicalizedResource st
 }
 
 func (conn Conn) signURL(method HTTPMethod, bucketName, objectName string, expiration int64, params map[string]interface{}, headers map[string]string) string {
-	if conn.config.GetSecurityToken() != "" {
-		params[HTTPParamSecurityToken] = conn.config.GetSecurityToken()
+	akIf := conn.config.GetCredentialInf()
+	if akIf.GetSecurityToken() != "" {
+		params[HTTPParamSecurityToken] = akIf.GetSecurityToken()
 	}
 	subResource := conn.getSubResource(params)
 	canonicalizedResource := conn.url.getResource(bucketName, objectName, subResource)
@@ -309,10 +312,10 @@ func (conn Conn) signURL(method HTTPMethod, bucketName, objectName string, expir
 		}
 	}
 
-	signedStr := conn.getSignedStr(req, canonicalizedResource)
+	signedStr := conn.getSignedStr(req, canonicalizedResource, akIf.GetAccessKeySecret())
 
 	params[HTTPParamExpires] = strconv.FormatInt(expiration, 10)
-	params[HTTPParamAccessKeyID] = conn.config.GetAccessKeyID()
+	params[HTTPParamAccessKeyID] = akIf.GetAccessKeyID()
 	params[HTTPParamSignature] = signedStr
 
 	urlParams := conn.getURLParams(params)
@@ -327,12 +330,13 @@ func (conn Conn) signRtmpURL(bucketName, channelName, playlistName string, expir
 	expireStr := strconv.FormatInt(expiration, 10)
 	params[HTTPParamExpires] = expireStr
 
-	if conn.config.GetAccessKeyID() != "" {
-		params[HTTPParamAccessKeyID] = conn.config.GetAccessKeyID()
-		if conn.config.GetSecurityToken() != "" {
-			params[HTTPParamSecurityToken] = conn.config.GetSecurityToken()
+	akIf := conn.config.GetCredentialInf()
+	if akIf.GetAccessKeyID() != "" {
+		params[HTTPParamAccessKeyID] = akIf.GetAccessKeyID()
+		if akIf.GetSecurityToken() != "" {
+			params[HTTPParamSecurityToken] = akIf.GetSecurityToken()
 		}
-		signedStr := conn.getRtmpSignedStr(bucketName, channelName, playlistName, expiration, params)
+		signedStr := conn.getRtmpSignedStr(bucketName, channelName, playlistName, expiration, akIf.GetAccessKeySecret(), params)
 		params[HTTPParamSignature] = signedStr
 	}
 

+ 5 - 1
oss/conn_test.go

@@ -174,11 +174,15 @@ func (s *OssConnSuite) TestGetRtmpSignedStr(c *C) {
 	um.Init(endpoint, false, false)
 	conn := Conn{cfg, &um, nil}
 
+	defAkBuild := &defaultCredentialInfBuild{config: cfg}
+	cfg.UserAKBuild = defAkBuild
+
+	akIf := conn.config.GetCredentialInf()
 	//Anonymous
 	channelName := "test-get-rtmp-signed-str"
 	playlistName := "playlist.m3u8"
 	expiration := time.Now().Unix() + 3600
 	params := map[string]interface{}{}
-	signedStr := conn.getRtmpSignedStr(bucketName, channelName, playlistName, expiration, params)
+	signedStr := conn.getRtmpSignedStr(bucketName, channelName, playlistName, expiration, akIf.GetAccessKeySecret(), params)
 	c.Assert(signedStr, Equals, "")
 }