-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_create.go
177 lines (151 loc) · 4.92 KB
/
jwt_create.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
package handle
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/MicahParks/jwkset"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"github.com/MicahParks/magiclinksdev/magiclink"
"github.com/MicahParks/magiclinksdev/model"
"github.com/MicahParks/magiclinksdev/network/middleware/ctxkey"
"github.com/MicahParks/magiclinksdev/storage"
)
var (
// ErrRegisteredClaimProvided is returned when a registered claim is provided.
ErrRegisteredClaimProvided = errors.New("registered claims should not be provided")
)
// HandleJWTCreate handles the creation of a JWT.
func (s *Server) HandleJWTCreate(ctx context.Context, req model.ValidJWTCreateRequest) (model.JWTCreateResponse, error) {
jwtCreateArgs := req.JWTCreateArgs
edited, err := s.addRegisteredClaims(ctx, jwtCreateArgs)
if err != nil {
return model.JWTCreateResponse{}, fmt.Errorf("failed to add registered claims to JWT claims: %w", err)
}
meta, err := s.Store.ReadSigningKey(ctx)
if err != nil {
return model.JWTCreateResponse{}, fmt.Errorf("failed to get JWT signing key: %w", err)
}
method := magiclink.BestSigningMethod(meta.Key)
bytesClaims := SigningBytesClaims{
Claims: edited,
}
token := jwt.NewWithClaims(method, bytesClaims)
token.Header[jwkset.HeaderKID] = meta.KeyID
signed, err := token.SignedString(meta.Key)
if err != nil {
return model.JWTCreateResponse{}, fmt.Errorf("%w: %w", magiclink.ErrJWTSign, err)
}
response := model.JWTCreateResponse{
JWTCreateResults: model.JWTCreateResults{
JWT: signed,
},
RequestMetadata: model.RequestMetadata{
UUID: ctx.Value(ctxkey.RequestUUID).(uuid.UUID),
},
}
return response, nil
}
// SigningBytesClaims is a JWT claims type that allows for signing claims represented in bytes.
type SigningBytesClaims struct {
Claims json.RawMessage
}
// Valid helps implement the jwt.Claims interface.
func (s SigningBytesClaims) Valid() error {
valid := json.Valid(s.Claims)
if !valid {
return fmt.Errorf("%w: invalid JSON for JWT claims", model.ErrInvalidModel)
}
return nil
}
// MarshalJSON helps implement the json.Marshaler interface.
func (s SigningBytesClaims) MarshalJSON() ([]byte, error) {
return s.Claims, nil
}
func (s *Server) addRegisteredClaims(ctx context.Context, args model.ValidJWTCreateArgs) (json.RawMessage, error) {
sa, ok := ctx.Value(ctxkey.ServiceAccount).(model.ServiceAccount)
if !ok {
return nil, fmt.Errorf("%w: service account context not found", ctxkey.ErrCtxKey)
}
valid := json.Valid(args.JWTClaims)
if !valid {
return nil, fmt.Errorf("%w: invalid JSON for JWT claims", model.ErrInvalidModel)
}
n := time.Now()
now := jwt.NewNumericDate(n)
u, err := uuid.NewRandom()
if err != nil {
return nil, fmt.Errorf("failed to generate UUID: %w", err)
}
registeredClaims := jwt.RegisteredClaims{
Issuer: s.Config.Iss,
Subject: "", // Don't set.
Audience: jwt.ClaimStrings{sa.Aud.String()},
ExpiresAt: jwt.NewNumericDate(n.Add(args.JWTLifespan)),
NotBefore: now,
IssuedAt: now,
ID: u.String(),
}
registeredMarshaled, err := json.Marshal(registeredClaims)
if err != nil {
return nil, fmt.Errorf("failed to marshal registered claims: %w", err)
}
// https://tools.ietf.org/html/rfc7519#section-4.1
rfc5119 := []string{
"iss",
"sub",
"aud",
"exp",
"nbf",
"iat",
"jti",
}
edited := make(json.RawMessage, len(args.JWTClaims))
copy(edited, args.JWTClaims)
for _, attr := range rfc5119 {
if gjson.GetBytes(edited, attr).Exists() {
return nil, fmt.Errorf("%w: %s", ErrRegisteredClaimProvided, attr)
}
registered := gjson.GetBytes(registeredMarshaled, attr)
if registered.Exists() {
edited, err = sjson.SetBytes(edited, attr, registered.Value())
if err != nil {
return nil, fmt.Errorf("failed to set registered claims in JWT claims: %w", err)
}
} else {
edited, err = sjson.DeleteBytes(edited, attr)
if err != nil {
return nil, fmt.Errorf("failed to delete %s from registered claims: %w", attr, err)
}
}
}
return edited, nil
}
func (s *Server) createLinkArgs(ctx context.Context, args model.ValidLinkCreateArgs) (magiclink.CreateArgs[storage.MagicLinkCustomCreateArgs], error) {
var createArgs magiclink.CreateArgs[storage.MagicLinkCustomCreateArgs]
edited, err := s.addRegisteredClaims(ctx, args.JWTCreateArgs)
if err != nil {
return createArgs, fmt.Errorf("failed to add registered claims to JWT claims: %w", err)
}
claims := SigningBytesClaims{
Claims: edited,
}
meta, err := s.Store.ReadSigningKey(ctx)
if err != nil {
return createArgs, fmt.Errorf("failed to get JWT signing key: %w", err)
}
createArgs = magiclink.CreateArgs[storage.MagicLinkCustomCreateArgs]{
Custom: storage.MagicLinkCustomCreateArgs{
Expires: time.Now().Add(args.LinkLifespan),
},
JWTClaims: claims,
JWTKeyID: &meta.KeyID,
RedirectQueryKey: args.RedirectQueryKey,
RedirectURL: args.RedirectURL,
}
return createArgs, nil
}