-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magic_link_test.go
209 lines (188 loc) · 6.37 KB
/
magic_link_test.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
package magiclinksdev_test
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rsa"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/MicahParks/jwkset"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
mld "github.com/MicahParks/magiclinksdev"
"github.com/MicahParks/magiclinksdev/model"
"github.com/MicahParks/magiclinksdev/network"
"github.com/MicahParks/magiclinksdev/network/middleware"
"github.com/MicahParks/magiclinksdev/network/middleware/ctxkey"
)
type testClaims struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
func TestMagicLink(t *testing.T) {
const customRedirectQueryKey = "customRedirectQueryKey"
for _, tc := range []struct {
name string
keyfunc jwt.Keyfunc
reqBody model.MagicLinkCreateRequest
}{
{
name: "Default signing key",
keyfunc: func(token *jwt.Token) (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
tx, err := server.Store.Begin(ctx)
if err != nil {
panic(fmt.Sprintf("failed to begin transaction: %v", err))
}
//goland:noinspection GoUnhandledErrorResult
defer tx.Rollback(ctx)
ctx = context.WithValue(ctx, ctxkey.Tx, tx)
defaultKey, err := server.Store.SigningKeyDefaultRead(ctx)
if err != nil {
panic(fmt.Sprintf("failed to read default signing key: %v", err))
}
ed, ok := defaultKey.Key().(ed25519.PrivateKey)
if !ok {
panic("default signing key is not EdDSA private key")
}
err = tx.Commit(ctx)
if err != nil {
panic(fmt.Sprintf("failed to commit transaction: %v", err))
}
return ed.Public(), nil
},
reqBody: model.MagicLinkCreateRequest{
MagicLinkCreateParams: model.MagicLinkCreateParams{
JWTCreateParams: model.JWTCreateParams{
Claims: map[string]string{"foo": "bar"},
LifespanSeconds: 0,
},
LifespanSeconds: 0,
RedirectQueryKey: customRedirectQueryKey,
RedirectURL: "https://github.com/MicahParks/magiclinksdev",
},
},
},
{
name: "RSA signing key",
keyfunc: func(token *jwt.Token) (any, error) {
if token.Header["alg"] != jwkset.AlgRS256.String() {
panic(fmt.Sprintf("unexpected alg: %s", token.Header["alg"]))
}
for _, key := range assets.keys {
k, ok := key.Key().(*rsa.PrivateKey)
if ok {
return k.Public(), nil
}
}
panic("no RSA signing key")
},
reqBody: model.MagicLinkCreateRequest{
MagicLinkCreateParams: model.MagicLinkCreateParams{
JWTCreateParams: model.JWTCreateParams{
Alg: jwkset.AlgRS256.String(),
Claims: map[string]string{"foo": "bar"},
LifespanSeconds: 0,
},
LifespanSeconds: 0,
RedirectQueryKey: customRedirectQueryKey,
RedirectURL: "https://github.com/MicahParks/magiclinksdev",
},
},
},
} {
t.Run(tc.name, func(t *testing.T) {
marshaled, err := json.Marshal(tc.reqBody)
if err != nil {
t.Fatalf("Failed to marshal request body: %v", err)
}
recorder := httptest.NewRecorder()
u, err := assets.conf.Server.BaseURL.Get().Parse(network.PathMagicLinkCreate)
if err != nil {
t.Fatalf("Failed to parse URL: %v", err)
}
req := httptest.NewRequest(http.MethodPost, u.Path, bytes.NewReader(marshaled))
req.Header.Set(mld.HeaderContentType, mld.ContentTypeJSON)
req.Header.Set(middleware.APIKeyHeader, assets.sa.APIKey.String())
assets.mux.ServeHTTP(recorder, req)
if recorder.Code != http.StatusCreated {
t.Fatalf("Received non-200 status code: %d\n%s", recorder.Code, recorder.Body.String())
}
if recorder.Header().Get(mld.HeaderContentType) != mld.ContentTypeJSON {
t.Fatalf("Received non-JSON content type: %s", recorder.Header().Get(mld.HeaderContentType))
}
var linkCreateResponse model.MagicLinkCreateResponse
err = json.Unmarshal(recorder.Body.Bytes(), &linkCreateResponse)
if err != nil {
t.Fatalf("Failed to unmarshal response body: %v", err)
}
recorder = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, linkCreateResponse.MagicLinkCreateResults.MagicLink, nil)
reqSent := time.Now()
assets.mux.ServeHTTP(recorder, req)
if recorder.Code != http.StatusSeeOther {
t.Fatalf("Expected status code %d, got %d", http.StatusSeeOther, recorder.Code)
}
redirectURL, err := url.Parse(recorder.Header().Get("Location"))
if err != nil {
t.Fatalf("Failed to parse redirect URL in header: %v", err)
}
jwtB64 := redirectURL.Query().Get(customRedirectQueryKey)
if jwtB64 == "" {
t.Fatalf("Expected JWT in redirect URL query, got none")
}
claims := &testClaims{}
token, err := jwt.ParseWithClaims(jwtB64, claims, tc.keyfunc)
if err != nil {
t.Fatalf("Failed to parse JWT: %v", err)
}
if !token.Valid {
t.Fatalf("JWT is not valid")
}
if claims.Issuer != assets.conf.Server.Iss {
t.Fatalf("Expected issuer %q, got %q", assets.conf.Server.Iss, claims.Issuer)
}
if claims.Subject != "" {
t.Fatalf("Expected subject %q, got %q", "", claims.Subject)
}
if len(claims.Audience) != 1 || claims.Audience[0] != assets.sa.Aud.String() {
t.Fatalf("Expected audience %q, got %q", assets.sa.Aud.String(), claims.Audience)
}
checkTime(t, claims.ExpiresAt.Time, reqSent.Add(assets.conf.Server.Validation.JWTLifespanDefault.Get()))
checkTime(t, claims.NotBefore.Time, reqSent)
checkTime(t, claims.IssuedAt.Time, reqSent)
confirmUUID(t, claims.ID)
if claims.Foo != "bar" {
t.Fatalf("Expected foo to be bar, got %q", claims.Foo)
}
redirectURL.RawQuery = ""
if redirectURL.String() != tc.reqBody.MagicLinkCreateParams.RedirectURL {
t.Fatalf("Expected redirect URL %q, got %q", tc.reqBody.MagicLinkCreateParams.RedirectURL, redirectURL.String())
}
recorder = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, linkCreateResponse.MagicLinkCreateResults.MagicLink, nil)
assets.mux.ServeHTTP(recorder, req)
if recorder.Code != http.StatusNotFound {
t.Fatalf("Expected status code %d, got %d", http.StatusNotFound, recorder.Code)
}
})
}
}
func checkTime(t *testing.T, actual, expected time.Time) {
const leeway = time.Millisecond
if actual.Sub(expected) > leeway {
t.Fatalf("Expected time %q, got %q", expected, actual)
}
}
func confirmUUID(t *testing.T, u string) {
_, err := uuid.Parse(u)
if err != nil {
t.Fatalf("Failed to parse UUID: %v", err)
}
}