-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpsign_test.go
More file actions
216 lines (170 loc) · 5.88 KB
/
httpsign_test.go
File metadata and controls
216 lines (170 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// SPDX-License-Identifier: EUPL-1.2
package api_test
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-contrib/httpsign"
"github.com/gin-contrib/httpsign/crypto"
"github.com/gin-gonic/gin"
api "dappco.re/go/core/api"
)
const testSecretKey = "test-secret-key-for-hmac-sha256"
// testKeyID is the key ID used in HTTP signature tests.
var testKeyID = httpsign.KeyID("test-client")
// newTestSecrets builds a Secrets map with a single HMAC-SHA256 key for testing.
func newTestSecrets() httpsign.Secrets {
return httpsign.Secrets{
testKeyID: &httpsign.Secret{
Key: testSecretKey,
Algorithm: &crypto.HmacSha256{},
},
}
}
// signRequest constructs a valid HTTP Signature Authorization header for the
// given request, signing the specified headers with HMAC-SHA256 and the test
// secret key. The Date header is set to the current time if not already present.
func signRequest(req *http.Request, keyID httpsign.KeyID, secret string, headers []string) {
// Ensure a Date header exists.
if req.Header.Get("Date") == "" {
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
// Build the signing string in the same way the library does:
// each header as "header: value", joined by newlines.
var parts []string
for _, h := range headers {
var val string
switch h {
case "(request-target)":
val = fmt.Sprintf("%s %s", strings.ToLower(req.Method), req.URL.RequestURI())
case "host":
val = req.Host
default:
val = req.Header.Get(h)
}
parts = append(parts, fmt.Sprintf("%s: %s", h, val))
}
signingString := strings.Join(parts, "\n")
// Sign with HMAC-SHA256.
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(signingString))
sig := base64.StdEncoding.EncodeToString(mac.Sum(nil))
// Build the Authorization header.
authValue := fmt.Sprintf(
"Signature keyId=\"%s\",algorithm=\"hmac-sha256\",headers=\"%s\",signature=\"%s\"",
keyID,
strings.Join(headers, " "),
sig,
)
req.Header.Set("Authorization", authValue)
}
// ── WithHTTPSign ──────────────────────────────────────────────────────────
func TestWithHTTPSign_Good_ValidSignatureAccepted(t *testing.T) {
gin.SetMode(gin.TestMode)
// Use only (request-target) and date as required headers, disable
// validators to keep the test focused on signature verification.
requiredHeaders := []string{"(request-target)", "date"}
e, _ := api.New(api.WithHTTPSign(
newTestSecrets(),
httpsign.WithRequiredHeaders(requiredHeaders),
httpsign.WithValidator(), // no validators — pure signature check
))
e.Register(&stubGroup{})
h := e.Handler()
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/stub/ping", nil)
signRequest(req, testKeyID, testSecretKey, requiredHeaders)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 for validly signed request, got %d (body: %s)", w.Code, w.Body.String())
}
}
func TestWithHTTPSign_Bad_InvalidSignatureRejected(t *testing.T) {
gin.SetMode(gin.TestMode)
requiredHeaders := []string{"(request-target)", "date"}
e, _ := api.New(api.WithHTTPSign(
newTestSecrets(),
httpsign.WithRequiredHeaders(requiredHeaders),
httpsign.WithValidator(),
))
e.Register(&stubGroup{})
h := e.Handler()
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/stub/ping", nil)
// Sign with the wrong secret so the signature is invalid.
signRequest(req, testKeyID, "wrong-secret-key", requiredHeaders)
h.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for invalid signature, got %d", w.Code)
}
}
func TestWithHTTPSign_Bad_MissingSignatureRejected(t *testing.T) {
gin.SetMode(gin.TestMode)
requiredHeaders := []string{"(request-target)", "date"}
e, _ := api.New(api.WithHTTPSign(
newTestSecrets(),
httpsign.WithRequiredHeaders(requiredHeaders),
httpsign.WithValidator(),
))
e.Register(&stubGroup{})
h := e.Handler()
w := httptest.NewRecorder()
// Send a request with no signature at all.
req, _ := http.NewRequest(http.MethodGet, "/stub/ping", nil)
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
h.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for missing signature, got %d", w.Code)
}
}
func TestWithHTTPSign_Good_CombinesWithOtherMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
requiredHeaders := []string{"(request-target)", "date"}
e, _ := api.New(
api.WithRequestID(),
api.WithHTTPSign(
newTestSecrets(),
httpsign.WithRequiredHeaders(requiredHeaders),
httpsign.WithValidator(),
),
)
e.Register(&stubGroup{})
h := e.Handler()
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/stub/ping", nil)
signRequest(req, testKeyID, testSecretKey, requiredHeaders)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d (body: %s)", w.Code, w.Body.String())
}
// Verify that WithRequestID also ran.
if w.Header().Get("X-Request-ID") == "" {
t.Fatal("expected X-Request-ID header from WithRequestID")
}
}
func TestWithHTTPSign_Ugly_UnknownKeyIDRejected(t *testing.T) {
gin.SetMode(gin.TestMode)
requiredHeaders := []string{"(request-target)", "date"}
e, _ := api.New(api.WithHTTPSign(
newTestSecrets(),
httpsign.WithRequiredHeaders(requiredHeaders),
httpsign.WithValidator(),
))
e.Register(&stubGroup{})
h := e.Handler()
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/stub/ping", nil)
// Sign with an unknown key ID that does not exist in the secrets map.
unknownKeyID := httpsign.KeyID("unknown-client")
signRequest(req, unknownKeyID, testSecretKey, requiredHeaders)
h.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for unknown key ID, got %d", w.Code)
}
}