Auth with global secret for admin endpoints

This commit is contained in:
simon987
2019-03-09 13:05:31 -05:00
parent e2ba51b77a
commit b095c92cfd
5 changed files with 118 additions and 14 deletions

View File

@@ -1 +1,64 @@
package api
import (
"bytes"
"crypto"
"crypto/hmac"
"encoding/hex"
"errors"
"github.com/valyala/fasthttp"
"math"
"os"
"time"
)
var Secret = []byte(getApiSecret())
func getApiSecret() string {
secret := os.Getenv("WS_BUCKET_SECRET")
if secret == "" {
return "default_secret"
} else {
return secret
}
}
func validateRequest(ctx *fasthttp.RequestCtx) error {
signature := ctx.Request.Header.Peek("X-Signature")
timeStampStr := string(ctx.Request.Header.Peek("Timestamp"))
if timeStampStr == "" {
return errors.New("date is not specified")
}
timestamp, err := time.Parse(time.RFC1123, timeStampStr)
if err != nil {
return err
}
if math.Abs(float64(timestamp.Unix()-time.Now().Unix())) > 60 {
return errors.New("invalid Timestamp")
}
var body []byte
if ctx.Request.Header.IsGet() {
body = ctx.Request.RequestURI()
} else {
body = ctx.Request.Body()
}
mac := hmac.New(crypto.SHA256.New, Secret)
mac.Write(body)
mac.Write([]byte(timeStampStr))
expectedMac := make([]byte, 64)
hex.Encode(expectedMac, mac.Sum(nil))
matches := bytes.Compare(expectedMac, signature) == 0
if !matches {
return errors.New("signature does not match")
}
return nil
}

View File

@@ -7,7 +7,8 @@ import (
)
type GenericResponse struct {
Ok bool `json:"ok"`
Ok bool `json:"ok"`
Message string `json:"message,omitempty"`
}
type AllocateUploadSlotRequest struct {

View File

@@ -22,10 +22,18 @@ var upgrader = websocket.FastHTTPUpgrader{
func (api *WebApi) AllocateUploadSlot(ctx *fasthttp.RequestCtx) {
//todo auth
err := validateRequest(ctx)
if err != nil {
ctx.Response.Header.SetStatusCode(401)
Json(GenericResponse{
Ok: false,
Message: err.Error(),
}, ctx)
return
}
req := &AllocateUploadSlotRequest{}
err := json.Unmarshal(ctx.Request.Body(), req)
err = json.Unmarshal(ctx.Request.Body(), req)
if err != nil {
ctx.Response.Header.SetStatusCode(400)
Json(GenericResponse{