-
Notifications
You must be signed in to change notification settings - Fork 27
/
formats.go
520 lines (417 loc) · 11.2 KB
/
formats.go
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package validation
import (
"encoding/base64"
"errors"
"fmt"
"net/mail"
"net/url"
"path"
"regexp"
"strings"
"time"
"github.com/iawaknahc/jsonschema/pkg/jsonpointer"
jsonschemaformat "github.com/iawaknahc/jsonschema/pkg/jsonschema/format"
"github.com/iawaknahc/originmatcher"
"golang.org/x/text/language"
"github.com/authgear/authgear-server/pkg/api/model"
"github.com/authgear/authgear-server/pkg/util/phone"
"github.com/authgear/authgear-server/pkg/util/rolesgroupsutil"
"github.com/authgear/authgear-server/pkg/util/secretcode"
"github.com/authgear/authgear-server/pkg/util/territoryutil"
web3util "github.com/authgear/authgear-server/pkg/util/web3"
)
func init() {
jsonschemaformat.DefaultChecker["phone"] = FormatPhone{}
jsonschemaformat.DefaultChecker["email-name-addr"] = FormatEmail{AllowName: true}
jsonschemaformat.DefaultChecker["uri"] = FormatURI{}
jsonschemaformat.DefaultChecker["http_origin"] = FormatHTTPOrigin{}
jsonschemaformat.DefaultChecker["http_origin_spec"] = FormatHTTPOriginSpec{}
jsonschemaformat.DefaultChecker["wechat_account_id"] = FormatWeChatAccountID{}
jsonschemaformat.DefaultChecker["bcp47"] = FormatBCP47{}
jsonschemaformat.DefaultChecker["timezone"] = FormatTimezone{}
jsonschemaformat.DefaultChecker["birthdate"] = FormatBirthdate{}
jsonschemaformat.DefaultChecker["iso3166-1-alpha-2"] = FormatAlpha2{}
jsonschemaformat.DefaultChecker["x_totp_code"] = secretcode.OOBOTPSecretCode
jsonschemaformat.DefaultChecker["x_oob_otp_code"] = secretcode.OOBOTPSecretCode
jsonschemaformat.DefaultChecker["x_verification_code"] = secretcode.OOBOTPSecretCode
jsonschemaformat.DefaultChecker["x_recovery_code"] = secretcode.RecoveryCode
jsonschemaformat.DefaultChecker["x_custom_attribute_pointer"] = FormatCustomAttributePointer{}
jsonschemaformat.DefaultChecker["x_picture"] = FormatPicture{}
jsonschemaformat.DefaultChecker["x_hook_uri"] = FormatHookURI{}
jsonschemaformat.DefaultChecker["google_tag_manager_container_id"] = FormatGoogleTagManagerContainerID{}
jsonschemaformat.DefaultChecker["x_web3_contract_id"] = FormatContractID{}
jsonschemaformat.DefaultChecker["x_web3_network_id"] = FormatNetworkID{}
jsonschemaformat.DefaultChecker["x_duration_string"] = FormatDurationString{}
jsonschemaformat.DefaultChecker["x_base64_url"] = FormatBase64URL{}
jsonschemaformat.DefaultChecker["x_re2_regex"] = FormatRe2Regex{}
jsonschemaformat.DefaultChecker["x_role_group_key"] = rolesgroupsutil.FormatKey{}
}
// FormatPhone checks if input is a phone number in E.164 format.
// If the input is not a string, it is not an error.
// To enforce string, use other JSON schema constructs.
// This design allows this format to validate optional phone number.
type FormatPhone struct{}
func (f FormatPhone) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
return phone.LegalAndValidParser.CheckE164(str)
}
// FormatEmail checks if input is an email address.
// If the input is not a string, it is not an error.
// To enforce string, use other JSON schema constructs.
// This design allows this format to validate optional email.
type FormatEmail struct {
AllowName bool
}
func (f FormatEmail) CheckFormat(value interface{}) error {
s, ok := value.(string)
if !ok {
return nil
}
addr, err := mail.ParseAddress(s)
if err != nil {
return err
}
if !f.AllowName && addr.Name != "" {
return errors.New("input email must not have name")
}
return nil
}
// FormatURI checks if input is an absolute URI.
type FormatURI struct {
}
func (f FormatURI) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
u, err := url.Parse(str)
if err != nil {
return err
}
if u.Scheme == "" || u.Host == "" {
return errors.New("input URL must be absolute")
}
p := u.EscapedPath()
return FormatAbsolutePath{}.CheckFormat(p)
}
type FormatPicture struct{}
func (FormatPicture) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
u, err := url.Parse(str)
if err != nil {
return err
}
switch u.Scheme {
case "http":
fallthrough
case "https":
return FormatURI{}.CheckFormat(value)
case "authgearimages":
if u.Host != "" {
return errors.New("authgearimages URI does not have host")
}
p := u.EscapedPath()
return FormatAbsolutePath{}.CheckFormat(p)
default:
return fmt.Errorf("invalid scheme: %v", u.Scheme)
}
}
// FormatHTTPOrigin checks if input is a valid origin with http/https scheme,
// host and optional port only.
type FormatHTTPOrigin struct {
}
func (f FormatHTTPOrigin) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
u, err := url.Parse(str)
if err != nil {
return err
}
if u.Scheme != "http" && u.Scheme != "https" {
return errors.New("expect input URL with scheme http / https")
}
if u.Host == "" {
return errors.New("expect input URL with non-empty host")
}
err = errors.New("expect input URL without user info, path, query and fragment")
if u.User != nil {
return err
}
if u.Path != "" || u.RawPath != "" {
return err
}
if u.RawQuery != "" {
return err
}
if u.Fragment != "" || u.RawFragment != "" {
return err
}
return nil
}
type FormatHTTPOriginSpec struct{}
func (FormatHTTPOriginSpec) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
err := originmatcher.CheckValidSpecStrict(str)
if err != nil {
return err
}
return nil
}
// FormatWeChatAccountID checks if input start with gh_.
type FormatWeChatAccountID struct {
}
func (f FormatWeChatAccountID) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
if !strings.HasPrefix(str, "gh_") {
return errors.New("expect WeChat account id start with gh_")
}
return nil
}
type FormatBCP47 struct{}
func (f FormatBCP47) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
tag, err := language.Parse(str)
if err != nil {
return fmt.Errorf("invalid BCP 47 tag: %w", err)
}
canonical := tag.String()
if str != canonical {
return fmt.Errorf("non-canonical BCP 47 tag: %v != %v", str, canonical)
}
return nil
}
type FormatTimezone struct{}
func (FormatTimezone) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
hasSlash := strings.Contains(str, "/")
if !hasSlash {
return fmt.Errorf("valid timezone name has at least 1 slash: %#v", str)
}
_, err := time.LoadLocation(str)
if err != nil {
return fmt.Errorf("invalid timezone name: %w", err)
}
return nil
}
type FormatBirthdate struct{}
func (FormatBirthdate) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
if _, err := time.Parse("2006-01-02", str); err == nil {
return nil
}
if _, err := time.Parse("0000-01-02", str); err == nil {
return nil
}
if _, err := time.Parse("--01-02", str); err == nil {
return nil
}
if _, err := time.Parse("2006", str); err == nil {
return nil
}
return fmt.Errorf("invalid birthdate: %#v", str)
}
type FormatAlpha2 struct{}
func (FormatAlpha2) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
for _, allowed := range territoryutil.Alpha2 {
if allowed == str {
return nil
}
}
return fmt.Errorf("invalid ISO 3166-1 alpha-2 code: %#v", str)
}
type FormatCustomAttributePointer struct{}
func (FormatCustomAttributePointer) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
p, err := jsonpointer.Parse(str)
if err != nil {
return err
}
if len(p) != 1 {
return fmt.Errorf("custom attribute pointer must be one-level but found %v", len(p))
}
var runes []rune
for _, r := range p[0] {
runes = append(runes, r)
}
if len(runes) <= 0 {
return fmt.Errorf("custom attribute pointer must not be empty")
}
checkStart := func(r rune) bool {
return (r >= 'a' && r <= 'z')
}
checkEnd := func(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
}
check := func(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || (r == '_')
}
last := len(runes) - 1
for i, r := range runes {
var checkFunc func(rune) bool
switch i {
case 0:
checkFunc = checkStart
case last:
checkFunc = checkEnd
default:
checkFunc = check
}
if !checkFunc(r) {
return fmt.Errorf("invalid character at %v: %#v", i, string(r))
}
}
return nil
}
type FormatGoogleTagManagerContainerID struct{}
func (FormatGoogleTagManagerContainerID) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
if !strings.HasPrefix(str, "GTM-") {
return errors.New("expect google tag manager container ID to start with GTM-")
}
return nil
}
type FormatContractID struct{}
func (FormatContractID) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
contractID, err := web3util.ParseContractID(str)
if err != nil {
return fmt.Errorf("invalid contract ID: %#v", str)
}
if contractID.Blockchain == "ethereum" {
if _, ok := model.ParseEthereumNetwork(contractID.Network); !ok {
return fmt.Errorf("invalid ethereum chain ID: %#v", contractID.Network)
}
}
return nil
}
type FormatNetworkID struct{}
func (FormatNetworkID) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
contractID, err := web3util.ParseContractID(str)
if err != nil {
return fmt.Errorf("invalid network ID: %#v", str)
}
if contractID.Address != "0x0" {
return fmt.Errorf("invalid network ID: %#v", str)
}
return nil
}
type FormatAbsolutePath struct{}
func (FormatAbsolutePath) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
if str == "" {
str = "/"
}
hasTrailingSlash := strings.HasSuffix(str, "/")
cleaned := path.Clean(str)
if hasTrailingSlash && !strings.HasSuffix(cleaned, "/") {
cleaned = cleaned + "/"
}
if !path.IsAbs(str) || cleaned != str {
return fmt.Errorf("invalid path: %v", str)
}
return nil
}
type FormatHookURI struct{}
func (FormatHookURI) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
u, err := url.Parse(str)
if err != nil {
return err
}
switch u.Scheme {
case "http", "https":
return FormatURI{}.CheckFormat(value)
case "authgeardeno":
if u.Host != "" {
return fmt.Errorf("authgeardeno URI does not have host")
}
p := u.EscapedPath()
return FormatAbsolutePath{}.CheckFormat(p)
default:
return fmt.Errorf("invalid scheme: %v", u.Scheme)
}
}
type FormatDurationString struct{}
func (FormatDurationString) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
d, err := time.ParseDuration(str)
if err != nil {
return err
} else if d <= 0 {
return fmt.Errorf("non-positive duration %q", str)
}
return nil
}
type FormatBase64URL struct{}
func (FormatBase64URL) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
_, err := base64.RawURLEncoding.Strict().DecodeString(str)
if err != nil {
return err
}
return nil
}
type FormatRe2Regex struct{}
func (FormatRe2Regex) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
_, err := regexp.Compile(str)
if err != nil {
return err
}
return nil
}