/
serialize.go
264 lines (227 loc) · 6.88 KB
/
serialize.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
package jwt
import (
"fmt"
"github.com/lestrrat-go/jwx/v2/internal/json"
"github.com/lestrrat-go/jwx/v2/jwe"
"github.com/lestrrat-go/jwx/v2/jws"
)
type SerializeCtx interface {
Step() int
Nested() bool
}
type serializeCtx struct {
step int
nested bool
}
func (ctx *serializeCtx) Step() int {
return ctx.step
}
func (ctx *serializeCtx) Nested() bool {
return ctx.nested
}
type SerializeStep interface {
Serialize(SerializeCtx, interface{}) (interface{}, error)
}
// errStep is always an error. used to indicate that a method like
// serializer.Sign or Encrypt already errored out on configuration
type errStep struct {
err error
}
func (e errStep) Serialize(_ SerializeCtx, _ interface{}) (interface{}, error) {
return nil, e.err
}
// Serializer is a generic serializer for JWTs. Whereas other conveinience
// functions can only do one thing (such as generate a JWS signed JWT),
// Using this construct you can serialize the token however you want.
//
// By default the serializer only marshals the token into a JSON payload.
// You must set up the rest of the steps that should be taken by the
// serializer.
//
// For example, to marshal the token into JSON, then apply JWS and JWE
// in that order, you would do:
//
// serialized, err := jwt.NewSerialer().
// Sign(jwa.RS256, key).
// Encrypt(jwa.RSA_OAEP, key.PublicKey).
// Serialize(token)
//
// The `jwt.Sign()` function is equivalent to
//
// serialized, err := jwt.NewSerializer().
// Sign(...args...).
// Serialize(token)
type Serializer struct {
steps []SerializeStep
}
// NewSerializer creates a new empty serializer.
func NewSerializer() *Serializer {
return &Serializer{}
}
// Reset clears all of the registered steps.
func (s *Serializer) Reset() *Serializer {
s.steps = nil
return s
}
// Step adds a new Step to the serialization process
func (s *Serializer) Step(step SerializeStep) *Serializer {
s.steps = append(s.steps, step)
return s
}
type jsonSerializer struct{}
func (jsonSerializer) Serialize(_ SerializeCtx, v interface{}) (interface{}, error) {
token, ok := v.(Token)
if !ok {
return nil, fmt.Errorf(`invalid input: expected jwt.Token`)
}
buf, err := json.Marshal(token)
if err != nil {
return nil, fmt.Errorf(`failed to serialize as JSON`)
}
return buf, nil
}
type genericHeader interface {
Get(string) (interface{}, bool)
Set(string, interface{}) error
}
func setTypeOrCty(ctx SerializeCtx, hdrs genericHeader) error {
// cty and typ are common between JWE/JWS, so we don't use
// the constants in jws/jwe package here
const typKey = `typ`
const ctyKey = `cty`
if ctx.Step() == 1 {
// We are executed immediately after json marshaling
if _, ok := hdrs.Get(typKey); !ok {
if err := hdrs.Set(typKey, `JWT`); err != nil {
return fmt.Errorf(`failed to set %s key to "JWT": %w`, typKey, err)
}
}
} else {
if ctx.Nested() {
// If this is part of a nested sequence, we should set cty = 'JWT'
// https://datatracker.ietf.org/doc/html/rfc7519#section-5.2
if err := hdrs.Set(ctyKey, `JWT`); err != nil {
return fmt.Errorf(`failed to set %s key to "JWT": %w`, ctyKey, err)
}
}
}
return nil
}
type jwsSerializer struct {
options []jws.SignOption
}
func (s *jwsSerializer) Serialize(ctx SerializeCtx, v interface{}) (interface{}, error) {
payload, ok := v.([]byte)
if !ok {
return nil, fmt.Errorf(`expected []byte as input`)
}
for _, option := range s.options {
pc, ok := option.Value().(interface{ Protected(jws.Headers) jws.Headers })
if !ok {
continue
}
hdrs := pc.Protected(jws.NewHeaders())
if err := setTypeOrCty(ctx, hdrs); err != nil {
return nil, err // this is already wrapped
}
// JWTs MUST NOT use b64 = false
// https://datatracker.ietf.org/doc/html/rfc7797#section-7
if v, ok := hdrs.Get("b64"); ok {
if bval, bok := v.(bool); bok {
if !bval { // b64 = false
return nil, fmt.Errorf(`b64 cannot be false for JWTs`)
}
}
}
}
return jws.Sign(payload, s.options...)
}
func (s *Serializer) Sign(options ...SignOption) *Serializer {
var soptions []jws.SignOption
if l := len(options); l > 0 {
// we need to from SignOption to Option because ... reasons
// (todo: when go1.18 prevails, use type parameters
rawoptions := make([]Option, l)
for i, option := range options {
rawoptions[i] = option
}
converted, err := toSignOptions(rawoptions...)
if err != nil {
return s.Step(errStep{fmt.Errorf(`(jwt.Serializer).Sign: failed to convert options into jws.SignOption: %w`, err)})
}
soptions = converted
}
return s.sign(soptions...)
}
func (s *Serializer) sign(options ...jws.SignOption) *Serializer {
return s.Step(&jwsSerializer{
options: options,
})
}
type jweSerializer struct {
options []jwe.EncryptOption
}
func (s *jweSerializer) Serialize(ctx SerializeCtx, v interface{}) (interface{}, error) {
payload, ok := v.([]byte)
if !ok {
return nil, fmt.Errorf(`expected []byte as input`)
}
hdrs := jwe.NewHeaders()
if err := setTypeOrCty(ctx, hdrs); err != nil {
return nil, err // this is already wrapped
}
options := append([]jwe.EncryptOption{jwe.WithMergeProtectedHeaders(true), jwe.WithProtectedHeaders(hdrs)}, s.options...)
return jwe.Encrypt(payload, options...)
}
// Encrypt specifies the JWT to be serialized as an encrypted payload.
//
// One notable difference between this method and `jwe.Encrypt()` is that
// while `jwe.Encrypt()` OVERWRITES the previous headers when `jwe.WithProtectedHeaders()`
// is provided, this method MERGES them. This is due to the fact that we
// MUST add some extra headers to construct a proper JWE message.
// Be careful when you pass multiple `jwe.EncryptOption`s.
func (s *Serializer) Encrypt(options ...EncryptOption) *Serializer {
var eoptions []jwe.EncryptOption
if l := len(options); l > 0 {
// we need to from SignOption to Option because ... reasons
// (todo: when go1.18 prevails, use type parameters
rawoptions := make([]Option, l)
for i, option := range options {
rawoptions[i] = option
}
converted, err := toEncryptOptions(rawoptions...)
if err != nil {
return s.Step(errStep{fmt.Errorf(`(jwt.Serializer).Encrypt: failed to convert options into jwe.EncryptOption: %w`, err)})
}
eoptions = converted
}
return s.encrypt(eoptions...)
}
func (s *Serializer) encrypt(options ...jwe.EncryptOption) *Serializer {
return s.Step(&jweSerializer{
options: options,
})
}
func (s *Serializer) Serialize(t Token) ([]byte, error) {
steps := make([]SerializeStep, len(s.steps)+1)
steps[0] = jsonSerializer{}
for i, step := range s.steps {
steps[i+1] = step
}
var ctx serializeCtx
ctx.nested = len(s.steps) > 1
var payload interface{} = t
for i, step := range steps {
ctx.step = i
v, err := step.Serialize(&ctx, payload)
if err != nil {
return nil, fmt.Errorf(`failed to serialize token at step #%d: %w`, i+1, err)
}
payload = v
}
res, ok := payload.([]byte)
if !ok {
return nil, fmt.Errorf(`invalid serialization produced`)
}
return res, nil
}