admin: Add service Set Credentials API (#3580)

This commit is contained in:
Anis Elleuch
2017-01-17 23:25:59 +01:00
committed by Harshavardhana
parent 20a65981bd
commit f803bb4b3d
13 changed files with 317 additions and 27 deletions

View File

@@ -18,6 +18,8 @@ package cmd
import (
"encoding/json"
"encoding/xml"
"io/ioutil"
"net/http"
"net/url"
"strconv"
@@ -84,6 +86,76 @@ func (adminAPI adminAPIHandlers) ServiceRestartHandler(w http.ResponseWriter, r
sendServiceCmd(globalAdminPeers, serviceRestart)
}
// setCredsReq request
type setCredsReq struct {
Username string `xml:"username"`
Password string `xml:"password"`
}
// ServiceCredsHandler - POST /?service
// HTTP header x-minio-operation: creds
// ----------
// Update credentials in a minio server. In a distributed setup, update all the servers
// in the cluster.
func (adminAPI adminAPIHandlers) ServiceCredentialsHandler(w http.ResponseWriter, r *http.Request) {
// Authenticate request
adminAPIErr := checkRequestAuthType(r, "", "", "")
if adminAPIErr != ErrNone {
writeErrorResponse(w, adminAPIErr, r.URL)
return
}
// Avoid setting new credentials when they are already passed
// by the environnement
if globalEnvAccessKey != "" || globalEnvSecretKey != "" {
writeErrorResponse(w, ErrMethodNotAllowed, r.URL)
return
}
// Load request body
inputData, err := ioutil.ReadAll(r.Body)
if err != nil {
writeErrorResponse(w, ErrInternalError, r.URL)
return
}
// Unmarshal request body
var req setCredsReq
err = xml.Unmarshal(inputData, &req)
if err != nil {
errorIf(err, "Cannot unmarshal credentials request")
writeErrorResponse(w, ErrMalformedXML, r.URL)
return
}
// Check passed credentials
cred, err := getCredential(req.Username, req.Password)
switch err {
case errInvalidAccessKeyLength:
writeErrorResponse(w, ErrAdminInvalidAccessKey, r.URL)
return
case errInvalidSecretKeyLength:
writeErrorResponse(w, ErrAdminInvalidSecretKey, r.URL)
return
}
// Notify all other Minio peers to update credentials
updateErrs := updateCredsOnPeers(cred)
for peer, err := range updateErrs {
errorIf(err, "Unable to update credentials on peer %s.", peer)
}
// Update local credentials
serverConfig.SetCredential(cred)
if err = serverConfig.Save(); err != nil {
writeErrorResponse(w, ErrInternalError, r.URL)
return
}
// At this stage, the operation is successful, return 200 OK
w.WriteHeader(http.StatusOK)
}
// validateLockQueryParams - Validates query params for list/clear locks management APIs.
func validateLockQueryParams(vars url.Values) (string, string, time.Duration, APIErrorCode) {
bucket := vars.Get(string(mgmtBucket))

View File

@@ -19,6 +19,8 @@ package cmd
import (
"bytes"
"encoding/json"
"encoding/xml"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
@@ -33,8 +35,8 @@ type cmdType int
const (
statusCmd cmdType = iota
stopCmd
restartCmd
setCreds
)
// String - String representation for cmdType
@@ -42,10 +44,10 @@ func (c cmdType) String() string {
switch c {
case statusCmd:
return "status"
case stopCmd:
return "stop"
case restartCmd:
return "restart"
case setCreds:
return "set-credentials"
}
return ""
}
@@ -58,6 +60,8 @@ func (c cmdType) apiMethod() string {
return "GET"
case restartCmd:
return "POST"
case setCreds:
return "POST"
}
return "GET"
}
@@ -86,15 +90,19 @@ func testServiceSignalReceiver(cmd cmdType, t *testing.T) {
// getServiceCmdRequest - Constructs a management REST API request for service
// subcommands for a given cmdType value.
func getServiceCmdRequest(cmd cmdType, cred credential) (*http.Request, error) {
func getServiceCmdRequest(cmd cmdType, cred credential, body []byte) (*http.Request, error) {
req, err := newTestRequest(cmd.apiMethod(), "/?service", 0, nil)
if err != nil {
return nil, err
}
// Set body
req.Body = ioutil.NopCloser(bytes.NewReader(body))
// minioAdminOpHeader is to identify the request as a
// management REST API request.
req.Header.Set(minioAdminOpHeader, cmd.String())
req.Header.Set("X-Amz-Content-Sha256", getSHA256Hash(body))
// management REST API uses signature V4 for authentication.
err = signRequestV4(req, cred.AccessKey, cred.SecretKey)
@@ -106,7 +114,7 @@ func getServiceCmdRequest(cmd cmdType, cred credential) (*http.Request, error) {
// testServicesCmdHandler - parametrizes service subcommand tests on
// cmdType value.
func testServicesCmdHandler(cmd cmdType, t *testing.T) {
func testServicesCmdHandler(cmd cmdType, args map[string]interface{}, t *testing.T) {
// reset globals.
// this is to make sure that the tests are not affected by modified value.
resetTestGlobals()
@@ -147,19 +155,25 @@ func testServicesCmdHandler(cmd cmdType, t *testing.T) {
// Setting up a go routine to simulate ServerMux's
// handleServiceSignals for stop and restart commands.
switch cmd {
case stopCmd, restartCmd:
if cmd == restartCmd {
go testServiceSignalReceiver(cmd, t)
}
credentials := serverConfig.GetCredential()
adminRouter := router.NewRouter()
registerAdminRouter(adminRouter)
rec := httptest.NewRecorder()
req, err := getServiceCmdRequest(cmd, credentials)
var body []byte
if cmd == setCreds {
body, _ = xml.Marshal(setCredsReq{Username: args["username"].(string), Password: args["password"].(string)})
}
req, err := getServiceCmdRequest(cmd, credentials, body)
if err != nil {
t.Fatalf("Failed to build service status request %v", err)
}
rec := httptest.NewRecorder()
adminRouter.ServeHTTP(rec, req)
if cmd == statusCmd {
@@ -173,20 +187,37 @@ func testServicesCmdHandler(cmd cmdType, t *testing.T) {
}
}
if cmd == setCreds {
// Check if new credentials are set
cred := serverConfig.GetCredential()
if cred.AccessKey != args["username"].(string) {
t.Errorf("Wrong access key, expected = %s, found = %s", args["username"].(string), cred.AccessKey)
}
if cred.SecretKey != args["password"].(string) {
t.Errorf("Wrong secret key, expected = %s, found = %s", args["password"].(string), cred.SecretKey)
}
}
if rec.Code != http.StatusOK {
t.Errorf("Expected to receive %d status code but received %d",
http.StatusOK, rec.Code)
resp, _ := ioutil.ReadAll(rec.Body)
t.Errorf("Expected to receive %d status code but received %d. Body (%s)",
http.StatusOK, rec.Code, string(resp))
}
}
// Test for service status management REST API.
func TestServiceStatusHandler(t *testing.T) {
testServicesCmdHandler(statusCmd, t)
testServicesCmdHandler(statusCmd, nil, t)
}
// Test for service restart management REST API.
func TestServiceRestartHandler(t *testing.T) {
testServicesCmdHandler(restartCmd, t)
testServicesCmdHandler(restartCmd, nil, t)
}
func TestServiceSetCreds(t *testing.T) {
testServicesCmdHandler(setCreds, map[string]interface{}{"username": "minio", "password": "minio123"}, t)
}
// mkLockQueryVal - helper function to build lock query param.

View File

@@ -36,6 +36,8 @@ func registerAdminRouter(mux *router.Router) {
// Service restart
adminRouter.Methods("POST").Queries("service", "").Headers(minioAdminOpHeader, "restart").HandlerFunc(adminAPI.ServiceRestartHandler)
// Service update credentials
adminRouter.Methods("POST").Queries("service", "").Headers(minioAdminOpHeader, "set-credentials").HandlerFunc(adminAPI.ServiceCredentialsHandler)
/// Lock operations

View File

@@ -140,6 +140,9 @@ const (
// Add new extended error codes here.
// Please open a https://github.com/minio/minio/issues before adding
// new error codes here.
ErrAdminInvalidAccessKey
ErrAdminInvalidSecretKey
)
// error code to APIError structure, these fields carry respective
@@ -574,6 +577,17 @@ var errorCodeResponse = map[APIErrorCode]APIError{
Description: "Server not initialized, please try again.",
HTTPStatusCode: http.StatusServiceUnavailable,
},
ErrAdminInvalidAccessKey: {
Code: "XMinioAdminInvalidAccessKey",
Description: "The access key is invalid.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrAdminInvalidSecretKey: {
Code: "XMinioAdminInvalidSecretKey",
Description: "The secret key is invalid.",
HTTPStatusCode: http.StatusBadRequest,
},
// Add your error structure here.
}

View File

@@ -101,6 +101,12 @@ var (
// Minio server user agent string.
globalServerUserAgent = "Minio/" + ReleaseTag + " (" + runtime.GOOS + "; " + runtime.GOARCH + ")"
// Access key passed from the environment
globalEnvAccessKey = os.Getenv("MINIO_ACCESS_KEY")
// Secret key passed from the environment
globalEnvSecretKey = os.Getenv("MINIO_SECRET_KEY")
// Add new variable global values here.
)

View File

@@ -190,13 +190,11 @@ func minioInit(ctx *cli.Context) {
enableLoggers()
// Fetch access keys from environment variables and update the config.
accessKey := os.Getenv("MINIO_ACCESS_KEY")
secretKey := os.Getenv("MINIO_SECRET_KEY")
if accessKey != "" && secretKey != "" {
if globalEnvAccessKey != "" && globalEnvSecretKey != "" {
// Set new credentials.
serverConfig.SetCredential(credential{
AccessKey: accessKey,
SecretKey: secretKey,
AccessKey: globalEnvAccessKey,
SecretKey: globalEnvSecretKey,
})
}
if !isAccessKeyValid(serverConfig.GetCredential().AccessKey) {