api: More cleanups at WebAPI.

- Fixes a bug where bucketName was not denormalized.
- Remove unneeded functions from jwt.go
This commit is contained in:
Harshavardhana 2016-01-25 17:29:20 -08:00
parent f1ea609175
commit ae2f15c6d0
6 changed files with 117 additions and 61 deletions

View File

@ -1,3 +1,19 @@
/*
* Minio Cloud Storage, (C) 2016 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 package main
import ( import (
@ -12,7 +28,7 @@ type authHandler struct {
} }
// AuthHandler - // AuthHandler -
// Verify if authorization header has signature version '2', reject it cleanly. // Verify if authorization header is of form JWT, reject it otherwise.
func AuthHandler(h http.Handler) http.Handler { func AuthHandler(h http.Handler) http.Handler {
return authHandler{h} return authHandler{h}
} }
@ -20,11 +36,12 @@ func AuthHandler(h http.Handler) http.Handler {
// Ignore request if authorization header is not valid. // Ignore request if authorization header is not valid.
func (h authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (h authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Let the top level caller handle if the requests should be // Let the top level caller handle if the requests should be
// allowed. // allowed, if there are no Authorization headers.
if r.Header.Get("Authorization") == "" { if r.Header.Get("Authorization") == "" {
h.handler.ServeHTTP(w, r) h.handler.ServeHTTP(w, r)
return return
} }
// Validate Authorization header to be valid.
jwt := InitJWT() jwt := InitJWT()
token, err := jwtgo.ParseFromRequest(r, func(token *jwtgo.Token) (interface{}, error) { token, err := jwtgo.ParseFromRequest(r, func(token *jwtgo.Token) (interface{}, error) {
if _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok { if _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok {

85
jwt.go
View File

@ -1,35 +1,60 @@
/*
* Minio Cloud Storage, (C) 2016 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 package main
import ( import (
"crypto/rsa" "crypto/rsa"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"errors"
"io/ioutil" "io/ioutil"
"time" "time"
jwt "github.com/dgrijalva/jwt-go" jwtgo "github.com/dgrijalva/jwt-go"
"github.com/minio/minio-xl/pkg/probe"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
// JWT - jwt auth backend // JWT - jwt auth backend
type JWT struct { type JWT struct {
// Public value.
PublicKey *rsa.PublicKey
// private values.
privateKey *rsa.PrivateKey privateKey *rsa.PrivateKey
PublicKey *rsa.PublicKey
accessKeyID string accessKeyID string
secretAccessKey string secretAccessKey string
} }
const ( const (
jwtExpirationDelta = 10 jwtExpirationDelta = 10
expireOffset = 3600
) )
// InitJWT - init. // InitJWT - initialize.
func InitJWT() *JWT { func InitJWT() *JWT {
jwt := &JWT{ jwt := &JWT{
privateKey: getPrivateKey(), privateKey: getPrivateKey(),
PublicKey: getPublicKey(),
} }
// Validate if public key is of algorithm *rsa.PublicKey.
var ok bool
jwt.PublicKey, ok = jwt.privateKey.Public().(*rsa.PublicKey)
if !ok {
fatalIf(probe.NewError(errors.New("")), "Unsupported type of public key algorithm found.", nil)
}
// Load credentials configuration.
config, err := loadConfigV2() config, err := loadConfigV2()
fatalIf(err.Trace("JWT"), "Unable to load configuration file.", nil) fatalIf(err.Trace("JWT"), "Unable to load configuration file.", nil)
@ -39,9 +64,10 @@ func InitJWT() *JWT {
return jwt return jwt
} }
// GenerateToken - // GenerateToken - generates a new Json Web Token based on the incoming user id.
func (b *JWT) GenerateToken(userName string) (string, error) { func (b *JWT) GenerateToken(userName string) (string, error) {
token := jwt.New(jwt.SigningMethodRS512) token := jwtgo.New(jwtgo.SigningMethodRS512)
// Token expires in 10hrs.
token.Claims["exp"] = time.Now().Add(time.Hour * time.Duration(jwtExpirationDelta)).Unix() token.Claims["exp"] = time.Now().Add(time.Hour * time.Duration(jwtExpirationDelta)).Unix()
token.Claims["iat"] = time.Now().Unix() token.Claims["iat"] = time.Now().Unix()
token.Claims["sub"] = userName token.Claims["sub"] = userName
@ -52,32 +78,16 @@ func (b *JWT) GenerateToken(userName string) (string, error) {
return tokenString, nil return tokenString, nil
} }
// Authenticate - // Authenticate - authenticates the username and password.
func (b *JWT) Authenticate(args *LoginArgs) bool { func (b *JWT) Authenticate(username, password string) bool {
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(b.secretAccessKey), 10) hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(b.secretAccessKey), 10)
if args.Username == b.accessKeyID { if username == b.accessKeyID {
return bcrypt.CompareHashAndPassword(hashedPassword, []byte(args.Password)) == nil return bcrypt.CompareHashAndPassword(hashedPassword, []byte(password)) == nil
} }
return false return false
} }
// // getPrivateKey - get the generated private key.
func (b *JWT) getTokenRemainingValidity(timestamp interface{}) int {
if validity, ok := timestamp.(float64); ok {
tm := time.Unix(int64(validity), 0)
remainer := tm.Sub(time.Now())
if remainer > 0 {
return int(remainer.Seconds() + expireOffset)
}
}
return expireOffset
}
// Logout - logout is not implemented yet.
func (b *JWT) Logout(tokenString string) error {
return nil
}
func getPrivateKey() *rsa.PrivateKey { func getPrivateKey() *rsa.PrivateKey {
pemBytes, err := ioutil.ReadFile(mustGetPrivateKeyPath()) pemBytes, err := ioutil.ReadFile(mustGetPrivateKeyPath())
if err != nil { if err != nil {
@ -90,22 +100,3 @@ func getPrivateKey() *rsa.PrivateKey {
} }
return privateKeyImported return privateKeyImported
} }
func getPublicKey() *rsa.PublicKey {
pemBytes, err := ioutil.ReadFile(mustGetPublicKeyPath())
if err != nil {
panic(err)
}
data, _ := pem.Decode([]byte(pemBytes))
publicKeyImported, err := x509.ParsePKIXPublicKey(data.Bytes)
if err != nil {
panic(err)
}
rsaPub, ok := publicKeyImported.(*rsa.PublicKey)
if !ok {
panic(err)
}
return rsaPub
}

View File

@ -113,6 +113,15 @@ func (fs Filesystem) GetObjectMetadata(bucket, object string) (ObjectMetadata, *
return ObjectMetadata{}, probe.NewError(ObjectNameInvalid{Bucket: bucket, Object: bucket}) return ObjectMetadata{}, probe.NewError(ObjectNameInvalid{Bucket: bucket, Object: bucket})
} }
bucket = fs.denormalizeBucket(bucket)
bucketPath := filepath.Join(fs.path, bucket)
if _, e := os.Stat(bucketPath); e != nil {
if os.IsNotExist(e) {
return ObjectMetadata{}, probe.NewError(BucketNotFound{Bucket: bucket})
}
return ObjectMetadata{}, probe.NewError(e)
}
metadata, err := getMetadata(fs.path, bucket, object) metadata, err := getMetadata(fs.path, bucket, object)
if err != nil { if err != nil {
return ObjectMetadata{}, err.Trace(bucket, object) return ObjectMetadata{}, err.Trace(bucket, object)

View File

@ -1,3 +1,19 @@
/*
* Minio Cloud Storage, (C) 2016 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 package main
import ( import (
@ -46,9 +62,3 @@ func mustGetPrivateKeyPath() string {
fatalIf(err.Trace(), "Unable to get config path.", nil) fatalIf(err.Trace(), "Unable to get config path.", nil)
return webConfigDir + "/private.key" return webConfigDir + "/private.key"
} }
func mustGetPublicKeyPath() string {
webConfigDir, err := getWebConfigDir()
fatalIf(err.Trace(), "Unable to get config path.", nil)
return webConfigDir + "/public.key"
}

View File

@ -1,3 +1,19 @@
/*
* Minio Cloud Storage, (C) 2016 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 package main
import "time" import "time"

View File

@ -1,3 +1,19 @@
/*
* Minio Cloud Storage, (C) 2016 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 package main
import ( import (
@ -8,6 +24,8 @@ import (
jwtgo "github.com/dgrijalva/jwt-go" jwtgo "github.com/dgrijalva/jwt-go"
) )
// isAuthenticated validates if any incoming request to be a valid JWT
// authenticated request.
func isAuthenticated(req *http.Request) bool { func isAuthenticated(req *http.Request) bool {
jwt := InitJWT() jwt := InitJWT()
tokenRequest, err := jwtgo.ParseFromRequest(req, func(token *jwtgo.Token) (interface{}, error) { tokenRequest, err := jwtgo.ParseFromRequest(req, func(token *jwtgo.Token) (interface{}, error) {
@ -85,7 +103,7 @@ func (web *WebAPI) GetObjectURL(r *http.Request, args *GetObjectURLArgs, reply *
// Login - user login handler. // Login - user login handler.
func (web *WebAPI) Login(r *http.Request, args *LoginArgs, reply *AuthToken) error { func (web *WebAPI) Login(r *http.Request, args *LoginArgs, reply *AuthToken) error {
jwt := InitJWT() jwt := InitJWT()
if jwt.Authenticate(args) { if jwt.Authenticate(args.Username, args.Password) {
token, err := jwt.GenerateToken(args.Username) token, err := jwt.GenerateToken(args.Username)
if err != nil { if err != nil {
return err return err
@ -113,11 +131,6 @@ func (web *WebAPI) RefreshToken(r *http.Request, args *LoginArgs, reply *AuthTok
// Logout - user logout. // Logout - user logout.
func (web *WebAPI) Logout(r *http.Request, arg *string, reply *string) error { func (web *WebAPI) Logout(r *http.Request, arg *string, reply *string) error {
if isAuthenticated(r) { if isAuthenticated(r) {
jwt := InitJWT()
tokenString := r.Header.Get("Authorization")
if err := jwt.Logout(tokenString); err != nil {
return err
}
return nil return nil
} }
return errUnAuthorizedRequest return errUnAuthorizedRequest