1 package utils
2
3 import (
4 "regexp"
5 "testing"
6 )
7
8 func TestGenerateCodeVerifierWithLength(t *testing.T) {
9 tests := []struct {
10 name string
11 length int
12 wantErr bool
13 }{
14 {
15 name: "invalid length min",
16 length: 10,
17 wantErr: true,
18 },
19 {
20 name: "invalid length max",
21 length: 100,
22 wantErr: true,
23 },
24 {
25 name: "valid min length",
26 length: 32,
27 wantErr: false,
28 },
29 {
30 name: "valid max length",
31 length: 96,
32 wantErr: false,
33 },
34 {
35 name: "valid length",
36 length: 50,
37 wantErr: false,
38 },
39 }
40 for _, tt := range tests {
41 t.Run(tt.name, func(t *testing.T) {
42 got, err := GenerateCodeVerifierWithLength(tt.length)
43 if (err != nil) != tt.wantErr {
44 t.Errorf("GenerateCodeVerifierWithLength() error = %v, wantErr %v", err, tt.wantErr)
45 return
46 }
47 if err == nil {
48 if got == nil {
49 t.Errorf("GenerateCodeVerifierWithLength() = nil, value is needed")
50 } else {
51 verifyLengthAndPattern(got.CodeVerifier, t)
52 }
53 }
54 })
55 }
56 }
57
58 func TestPKCECodeVerifier_CodeChallengePlain(t *testing.T) {
59 tests := []struct {
60 name string
61 CodeVerifier string
62 want string
63 }{
64 {
65 name: "should be same as verifier",
66 CodeVerifier: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",
67 want: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",
68 },
69 }
70 for _, tt := range tests {
71 t.Run(tt.name, func(t *testing.T) {
72 v := &PKCECodeVerifier{
73 CodeVerifier: tt.CodeVerifier,
74 }
75
76 if got := v.CodeChallengePlain(); got != tt.want {
77 t.Errorf("PKCECodeVerifier.CodeChallengePlain() = %v, want %v", got, tt.want)
78 }
79 })
80 }
81 }
82
83
84 func TestPKCECodeVerifier_CodeChallengeS256(t *testing.T) {
85 cv, _ := GenerateCodeVerifierWithLength(50)
86
87 tests := []struct {
88 name string
89 CodeVerifier string
90 want string
91 }{
92 {
93 name: "should be sha256 of verifier",
94 CodeVerifier: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
95 want: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
96 },
97 {
98 name: "should be same as verifier",
99 CodeVerifier: cv.CodeVerifier,
100 want: "",
101 },
102 }
103 for _, tt := range tests {
104 t.Run(tt.name, func(t *testing.T) {
105 v := &PKCECodeVerifier{
106 CodeVerifier: tt.CodeVerifier,
107 }
108 got := v.CodeChallengeS256()
109 if tt.want != "" && got != tt.want {
110 t.Errorf("PKCECodeVerifier.CodeChallengeS256() = %v, want %v", got, tt.want)
111 }
112 verifyLengthAndPattern(got, t)
113 })
114 }
115 }
116
117 func verifyLengthAndPattern(val string, t *testing.T) {
118 if len(val) < 43 || len(val) > 128 {
119 t.Errorf("Invalid length: %v", val)
120 }
121 if _, e := regexp.Match(`[a-zA-Z0-9-_.~]+`, []byte(val)); e != nil {
122 t.Errorf("Invalid pattern: %v", val)
123 }
124 }
125
View as plain text