-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchallenge.go
More file actions
374 lines (341 loc) · 10.8 KB
/
challenge.go
File metadata and controls
374 lines (341 loc) · 10.8 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package mppx
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"regexp"
"strings"
)
// Challenge is a payment challenge issued by a server in a WWW-Authenticate header.
type Challenge struct {
// ID is the challenge identifier. When created with SecretKey it is HMAC-bound to its contents.
ID string `json:"id"`
// Realm identifies the server (e.g. hostname).
Realm string `json:"realm"`
// Method is the payment method name (e.g. "tempo", "stripe").
Method string `json:"method"`
// Intent is the intent type (e.g. "charge", "session").
Intent string `json:"intent"`
// Request contains method-specific payment parameters.
Request map[string]any `json:"request"`
// Digest is an optional SHA-256 digest of the HTTP request body ("sha-256=<base64>").
Digest string `json:"digest,omitempty"`
// Expires is an optional ISO 8601 expiration timestamp.
Expires string `json:"expires,omitempty"`
// Opaque contains optional server-defined correlation data. Clients MUST NOT modify this.
Opaque map[string]string `json:"opaque,omitempty"`
// Description is an optional human-readable payment description.
Description string `json:"description,omitempty"`
}
// ChallengeParams holds parameters for creating a new Challenge.
// Either ID or SecretKey must be provided.
type ChallengeParams struct {
// ID is an explicit challenge identifier.
ID string
// SecretKey causes the ID to be computed as HMAC-SHA256 over the challenge parameters.
// Use this instead of ID for stateless server-side verification.
SecretKey string
// Realm identifies the server.
Realm string
// Method is the payment method name.
Method string
// Intent is the intent type.
Intent string
// Request contains method-specific payment parameters.
Request map[string]any
// Digest is an optional body digest.
Digest string
// Expires is an optional ISO 8601 expiration timestamp.
Expires string
// Opaque contains optional server-defined correlation data.
Opaque map[string]string
// Description is an optional human-readable description.
Description string
}
// NewChallenge creates a Challenge. Either ID or SecretKey must be set in params.
func NewChallenge(p ChallengeParams) (Challenge, error) { //nolint:gocritic // Public API keeps value params for backward compatibility.
if p.ID == "" && p.SecretKey == "" {
return Challenge{}, errors.New("mpp: either ID or SecretKey must be provided")
}
id := p.ID
if p.SecretKey != "" {
id = computeChallengeHMAC(p.Realm, p.Method, p.Intent, p.Request, p.Expires, p.Digest, p.Opaque, p.SecretKey)
}
return Challenge{
ID: id,
Realm: p.Realm,
Method: p.Method,
Intent: p.Intent,
Request: p.Request,
Digest: p.Digest,
Expires: p.Expires,
Opaque: p.Opaque,
Description: p.Description,
}, nil
}
// SerializeChallenge serializes a Challenge to the WWW-Authenticate header value format.
//
// Format: Payment id="...", realm="...", method="...", intent="...", request="<base64url>"[, ...]
func SerializeChallenge(c Challenge) string { //nolint:gocritic // Public API keeps value params for backward compatibility.
parts := []string{
fmt.Sprintf("id=%q", c.ID),
fmt.Sprintf("realm=%q", c.Realm),
fmt.Sprintf("method=%q", c.Method),
fmt.Sprintf("intent=%q", c.Intent),
fmt.Sprintf("request=%q", SerializePaymentRequest(c.Request)),
}
if c.Description != "" {
parts = append(parts, fmt.Sprintf("description=%q", escapeAuthParamValue(c.Description)))
}
if c.Digest != "" {
parts = append(parts, fmt.Sprintf("digest=%q", c.Digest))
}
if c.Expires != "" {
parts = append(parts, fmt.Sprintf("expires=%q", c.Expires))
}
if len(c.Opaque) > 0 {
opaqueAny := stringMapToAnyMap(c.Opaque)
parts = append(parts, fmt.Sprintf("opaque=%q", SerializePaymentRequest(opaqueAny)))
}
return AuthSchemePaymentPrefix + strings.Join(parts, ", ")
}
// DeserializeChallenge parses the first Payment challenge from a WWW-Authenticate header value.
func DeserializeChallenge(header string) (Challenge, error) {
paramsStr, err := extractPaymentSchemeParams(header)
if err != nil {
return Challenge{}, err
}
params, err := parseAuthParams(paramsStr)
if err != nil {
return Challenge{}, err
}
return challengeFromParams(params)
}
// DeserializeChallenges parses all Payment challenges from a WWW-Authenticate header value
// that may contain multiple comma-separated challenges.
func DeserializeChallenges(header string) ([]Challenge, error) {
starts := findPaymentSchemeStarts(header)
if len(starts) == 0 {
return nil, errors.New("mpp: no Payment schemes found in header")
}
challenges := make([]Challenge, 0, len(starts))
for i, start := range starts {
var end int
if i+1 < len(starts) {
end = starts[i+1]
} else {
end = len(header)
}
chunk := strings.TrimRight(header[start:end], ", \t")
c, err := DeserializeChallenge(chunk)
if err != nil {
return nil, fmt.Errorf("mpp: error parsing challenge %d: %w", i, err)
}
challenges = append(challenges, c)
}
return challenges, nil
}
// VerifyChallenge verifies that a challenge's ID matches the expected HMAC-SHA256.
// Uses constant-time comparison to prevent timing attacks.
func VerifyChallenge(c Challenge, secretKey string) bool { //nolint:gocritic // Public API keeps value params for backward compatibility.
expected := computeChallengeHMAC(
c.Realm, c.Method, c.Intent, c.Request, c.Expires, c.Digest, c.Opaque, secretKey,
)
return hmac.Equal([]byte(c.ID), []byte(expected))
}
// computeChallengeHMAC computes HMAC-SHA256 over the challenge fields and returns the base64url result.
// Fields are joined with "|" in fixed positional order so the slot count is stable.
func computeChallengeHMAC(realm, method, intent string, request map[string]any, expires, digest string, opaque map[string]string, secretKey string) string {
reqStr := SerializePaymentRequest(request)
opaqueStr := ""
if len(opaque) > 0 {
opaqueStr = SerializePaymentRequest(stringMapToAnyMap(opaque))
}
input := strings.Join([]string{realm, method, intent, reqStr, expires, digest, opaqueStr}, "|")
mac := hmac.New(sha256.New, []byte(secretKey))
mac.Write([]byte(input))
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
var validMethodName = regexp.MustCompile(`^[a-z][a-z0-9:_-]*$`)
func challengeFromParams(params map[string]string) (Challenge, error) {
reqStr, ok := params["request"]
if !ok {
return Challenge{}, errors.New("mpp: missing 'request' parameter in challenge")
}
if method, ok := params["method"]; ok {
if !validMethodName.MatchString(method) {
return Challenge{}, fmt.Errorf("mpp: invalid method name %q: must match [a-z][a-z0-9:_-]*", method)
}
}
req, err := DeserializePaymentRequest(reqStr)
if err != nil {
return Challenge{}, fmt.Errorf("mpp: invalid request parameter: %w", err)
}
c := Challenge{
ID: params["id"],
Realm: params["realm"],
Method: params["method"],
Intent: params["intent"],
Request: req,
}
if v, ok := params["description"]; ok {
c.Description = v
}
if v, ok := params["digest"]; ok {
c.Digest = v
}
if v, ok := params["expires"]; ok {
c.Expires = v
}
if v, ok := params["opaque"]; ok {
opaqueMap, err := DeserializePaymentRequest(v)
if err == nil {
c.Opaque = anyMapToStringMap(opaqueMap)
}
}
return c, nil
}
// extractPaymentSchemeParams finds the first "Payment" scheme in a header value
// and returns the auth-params string that follows it.
func extractPaymentSchemeParams(header string) (string, error) {
lower := strings.ToLower(header)
const token = "payment"
for i := 0; i < len(lower); {
idx := strings.Index(lower[i:], token)
if idx == -1 {
break
}
abs := i + idx
next := abs + len(token)
// Verify a space follows the token
if next < len(lower) && isAuthSpace(lower[next]) {
// Verify proper boundary: start of string or preceded by comma
prefix := strings.TrimRight(header[:abs], " \t")
if prefix == "" || strings.HasSuffix(prefix, ",") {
start := next
for start < len(header) && isAuthSpace(rune(header[start])) {
start++
}
return header[start:], nil
}
}
i = abs + 1
}
return "", errors.New("mpp: missing " + AuthSchemePayment + " scheme in header")
}
// findPaymentSchemeStarts returns the start indices of all "Payment" auth-scheme occurrences.
func findPaymentSchemeStarts(header string) []int {
var starts []int
lower := strings.ToLower(header)
const token = "payment"
for i := 0; i < len(lower); {
idx := strings.Index(lower[i:], token)
if idx == -1 {
break
}
abs := i + idx
next := abs + len(token)
if next < len(lower) && isAuthSpace(lower[next]) {
starts = append(starts, abs)
}
i = abs + 1
}
return starts
}
// parseAuthParams parses a sequence of key="value" or key=token auth-params.
func parseAuthParams(input string) (map[string]string, error) { //nolint:gocyclo // Parsing WWW-Authenticate params is branch-heavy by design.
result := make(map[string]string)
i := 0
for i < len(input) {
// Skip whitespace and commas
for i < len(input) && (input[i] == ' ' || input[i] == '\t' || input[i] == ',') {
i++
}
if i >= len(input) {
break
}
// Read key
keyStart := i
for i < len(input) && isAuthTokenChar(input[i]) {
i++
}
key := input[keyStart:i]
if key == "" {
break
}
// Skip whitespace
for i < len(input) && (input[i] == ' ' || input[i] == '\t') {
i++
}
// Expect '='
if i >= len(input) || input[i] != '=' {
break // likely another auth scheme
}
i++
// Skip whitespace
for i < len(input) && (input[i] == ' ' || input[i] == '\t') {
i++
}
// Read value: quoted-string or token
var value string
if i < len(input) && input[i] == '"' {
i++ // skip opening quote
var sb strings.Builder
for i < len(input) {
c := input[i]
if c == '\\' && i+1 < len(input) {
sb.WriteByte(input[i+1])
i += 2
continue
}
if c == '"' {
i++
break
}
sb.WriteByte(c)
i++
}
value = sb.String()
} else {
j := i
for j < len(input) && input[j] != ',' {
j++
}
value = strings.TrimSpace(input[i:j])
i = j
}
if _, exists := result[key]; exists {
return nil, fmt.Errorf("mpp: duplicate parameter: %s", key)
}
result[key] = value
}
return result, nil
}
func isAuthSpace[T byte | rune](c T) bool {
return c == ' ' || c == '\t'
}
func isAuthTokenChar(c byte) bool {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '_' || c == '-'
}
func escapeAuthParamValue(s string) string {
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `"`, `\"`)
return s
}
func stringMapToAnyMap(m map[string]string) map[string]any {
result := make(map[string]any, len(m))
for k, v := range m {
result[k] = v
}
return result
}
func anyMapToStringMap(m map[string]any) map[string]string {
result := make(map[string]string, len(m))
for k, v := range m {
result[k] = fmt.Sprintf("%v", v)
}
return result
}