forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Request signing middleware (TykTechnologies#2328)
The feature is implemented using [Draft 10](https://tools.ietf.org/html/draft-cavage-http-signatures-10) `(request-target)` and all the headers of the request will be used for generating signature string. If request doesn't contain `Date` header, middleware will add one as it is required according to above draft. A new config option `request_signing` is added in API Definition to enable/disable request signing. It has following format ```json "request_signing": { "is_enabled": true, "key": "xxxx", "key_id": "1", "algorithm": "hmac-sha256" } ``` Following algorithms are supported: 1. `hmac-sha1` 2. `hmac-sha256` 3. `hmac-sha384` 4. `hmac-sha512` Fixes TykTechnologies#2234
- Loading branch information
1 parent
12fa088
commit f87150f
Showing
7 changed files
with
226 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
package gateway | ||
|
||
import ( | ||
"errors" | ||
"net/http" | ||
"strings" | ||
"time" | ||
) | ||
|
||
type RequestSigning struct { | ||
BaseMiddleware | ||
} | ||
|
||
func (s *RequestSigning) Name() string { | ||
return "RequestSigning" | ||
} | ||
|
||
func (s *RequestSigning) EnabledForSpec() bool { | ||
return s.Spec.RequestSigning.IsEnabled | ||
} | ||
|
||
var supportedAlgorithms = []string{"hmac-sha1", "hmac-sha256", "hmac-sha384", "hmac-sha512"} | ||
|
||
func generateHeaderList(r *http.Request) []string { | ||
headers := make([]string, len(r.Header)+1) | ||
|
||
headers[0] = "(request-target)" | ||
i := 1 | ||
|
||
for k := range r.Header { | ||
loweredCaseHeader := strings.ToLower(k) | ||
headers[i] = strings.TrimSpace(loweredCaseHeader) | ||
i++ | ||
} | ||
|
||
//Date header is must as per Signing HTTP Messages Draft | ||
if r.Header.Get("date") == "" { | ||
refDate := "Mon, 02 Jan 2006 15:04:05 MST" | ||
tim := time.Now().Format(refDate) | ||
|
||
r.Header.Set("date", tim) | ||
headers = append(headers, "date") | ||
} | ||
|
||
return headers | ||
} | ||
|
||
func (s *RequestSigning) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) { | ||
if s.Spec.RequestSigning.Secret == "" || s.Spec.RequestSigning.KeyId == "" || s.Spec.RequestSigning.Algorithm == "" { | ||
log.Error("Fields required for signing the request are missing") | ||
return errors.New("Fields required for signing the request are missing"), http.StatusInternalServerError | ||
} | ||
|
||
var algoList []string | ||
if len(s.Spec.HmacAllowedAlgorithms) > 0 { | ||
algoList = s.Spec.HmacAllowedAlgorithms | ||
} else { | ||
algoList = supportedAlgorithms | ||
} | ||
|
||
algorithmAllowed := false | ||
for _, alg := range algoList { | ||
if alg == s.Spec.RequestSigning.Algorithm { | ||
algorithmAllowed = true | ||
break | ||
} | ||
} | ||
if !algorithmAllowed { | ||
log.WithField("algorithm", s.Spec.RequestSigning.Algorithm).Error("Algorithm not supported") | ||
return errors.New("Request signing Algorithm is not supported"), http.StatusInternalServerError | ||
} | ||
|
||
headers := generateHeaderList(r) | ||
signatureString, err := generateHMACSignatureStringFromRequest(r, headers) | ||
if err != nil { | ||
log.Error(err) | ||
return err, http.StatusInternalServerError | ||
} | ||
|
||
strHeaders := strings.Join(headers, " ") | ||
encodedSignature := generateEncodedSignature(signatureString, s.Spec.RequestSigning.Secret, s.Spec.RequestSigning.Algorithm) | ||
|
||
//Generate Authorization header | ||
authHeader := "Signature " | ||
//Append keyId | ||
authHeader += "keyId=\"" + s.Spec.RequestSigning.KeyId + "\"," | ||
//Append algorithm | ||
authHeader += "algorithm=\"" + s.Spec.RequestSigning.Algorithm + "\"," | ||
//Append Headers | ||
authHeader += "headers=\"" + strHeaders + "\"," | ||
//Append signature | ||
authHeader += "signature=\"" + encodedSignature + "\"" | ||
|
||
r.Header.Set("Authorization", authHeader) | ||
log.Debug("Setting Authorization headers as =", authHeader) | ||
|
||
return nil, http.StatusOK | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
package gateway | ||
|
||
import ( | ||
"encoding/json" | ||
"testing" | ||
|
||
"github.com/TykTechnologies/tyk/test" | ||
"github.com/TykTechnologies/tyk/user" | ||
) | ||
|
||
var algoList = [4]string{"hmac-sha1", "hmac-sha256", "hmac-sha384", "hmac-sha512"} | ||
|
||
func generateSpec(algo string) { | ||
sessionKey := CreateSession(func(s *user.SessionState) { | ||
s.HMACEnabled = true | ||
s.HmacSecret = "9879879878787878" | ||
|
||
s.AccessRights = map[string]user.AccessDefinition{"protected": {APIID: "protected", Versions: []string{"v1"}}} | ||
|
||
}) | ||
|
||
BuildAndLoadAPI(func(spec *APISpec) { | ||
spec.APIID = "protected" | ||
spec.Name = "protected api" | ||
spec.Proxy.ListenPath = "/something" | ||
spec.EnableSignatureChecking = true | ||
spec.Auth.AuthHeaderName = "authorization" | ||
spec.HmacAllowedClockSkew = 5000 | ||
spec.UseKeylessAccess = false | ||
spec.UseBasicAuth = false | ||
spec.UseOauth2 = false | ||
|
||
version := spec.VersionData.Versions["v1"] | ||
version.UseExtendedPaths = true | ||
spec.VersionData.Versions["v1"] = version | ||
}, func(spec *APISpec) { | ||
spec.Proxy.ListenPath = "/test" | ||
spec.RequestSigning.IsEnabled = true | ||
spec.RequestSigning.KeyId = sessionKey | ||
spec.RequestSigning.Secret = "9879879878787878" | ||
spec.RequestSigning.Algorithm = algo | ||
|
||
version := spec.VersionData.Versions["v1"] | ||
json.Unmarshal([]byte(`{ | ||
"use_extended_paths": true, | ||
"extended_paths": { | ||
"url_rewrites": [{ | ||
"path": "/by_name", | ||
"match_pattern": "/by_name(.*)", | ||
"method": "GET", | ||
"rewrite_to": "tyk://protected api/get" | ||
}] | ||
} | ||
}`), &version) | ||
|
||
spec.VersionData.Versions["v1"] = version | ||
}) | ||
|
||
} | ||
|
||
func TestRequestSigning(t *testing.T) { | ||
ts := StartTest() | ||
defer ts.Close() | ||
|
||
for _, algo := range algoList { | ||
name := "Test with " + algo | ||
t.Run(name, func(t *testing.T) { | ||
|
||
generateSpec(algo) | ||
|
||
ts.Run(t, []test.TestCase{ | ||
{Path: "/test/by_name", Code: 200}, | ||
}...) | ||
}) | ||
} | ||
|
||
t.Run("Invalid algorithm", func(t *testing.T) { | ||
generateSpec("random") | ||
|
||
ts.Run(t, []test.TestCase{ | ||
{Path: "/test/by_name", Code: 500}, | ||
}...) | ||
}) | ||
|
||
t.Run("Invalid Date field", func(t *testing.T) { | ||
generateSpec("hmac-sha1") | ||
|
||
headers := map[string]string{"date": "Mon, 02 Jan 2006 15:04:05 GMT"} | ||
|
||
ts.Run(t, []test.TestCase{ | ||
{Path: "/test/by_name", Headers: headers, Code: 400}, | ||
}...) | ||
}) | ||
} |